2025.02.04

모두 정리가 되었지만 Byte Order 가 이해가 안돼서 다시 확인.

현재 코드기준

version + previous hash + root hash + ...

각 아이템은 보통의  Big Endian 이지만 전체로 보면 Little Endian이 되어야 한다.

string msg = “00112233…”
message[0] = 0x00;
message[1] = 0x11;
message[2] = 0x22;
message[3] = 0x33;

sha256_top에서 1byte 데이터를 4byte로 만들 때 Little로 바꾼다.

UINT msg = 0x00112233;

sha256_core에서 BIG_ENDIAN이 선언되어 있지 않기 때문에 Little을 다시 Big으로 바꾼다.

#if defined(BIG_ENDIAN)
#define GetData(x)  x
#else
#define GetData(x)  ENDIAN_REVERSE_ULONG(x)
#endif

W0:for (int j = 0; j < 16; j++)
W[j] = GetData(Message[j]);

따라서 W

W[0] = 0x33221100;

 


sha256 내부는 4byte Big Endian 처리

Little Endian 표시

02000000 ........................... Block version: 2

b6ff0b1b1680a2862a30ca44d346d9e8
910d334beb48ca0c0000000000000000 ... Hash of previous block's header
9d10aa52ee949386ca9385695f04ede2
70dda20810decd12bc9b048aaab31471 ... Merkle root

24d95a54 ........................... [Unix time][unix epoch time]: 1415239972
30c31b18 ........................... Target: 0x1bc330 * 256**(0x18-3)
fe9f0864 ........................... Nonce

 

메모리 맵

'IT > 비트코인' 카테고리의 다른 글

[비트코인] SHA256 & 채굴 (최종?)  (0) 2025.01.09
[비트코인] KISA SHA256 테스트  (0) 2025.01.02
[비트코인] Python 채굴  (0) 2022.02.05

2025.01.09

nonce가 자동으로 증가하도록 코드를 수정하다 보니 이제까지 의 예제 string이 뭔가 잘못되어 있다.

모든 정보가 string으로 된다고 했는데 다시 정리해서 보니 말이 안된다.


일단 다시 정리

해더는 4+32+32+4+4+4 => 80byte (640bit)

Hash가 00000000000000000024fb37364cbf81fd49cc2d51c09c75c35433c3a1945d04 인데

스트링으로 그대로 입력하면 64 char 되므로 32byte가 아니다.

보이는 것만 hex format


https://www.blockchain.com/explorer/blocks/btc/500000

#500000 자료로 다시 테스트

Version 0x20000000
Preve(#499999) 0000000000000000007962066dcd6675830883516bcf40047d42740a85eb2919
Merkle Root  31951c69428a95a46b517ffb0de12fec1bd0b2392aec07b64573e03ded31621f
Mined on 2017년 12월 19일 오전 3:35:25
Nonce 1,560,058,197
Bits 402,691,653
Hash  00000000000000000024fb37364cbf81fd49cc2d51c09c75c35433c3a1945d04

 

날짜를 숫자로 바꾸는 곳은 여기 

https://www.epochconverter.com/

 

Epoch Converter

Convert Unix Timestamps (and many other date formats) to regular dates.

www.epochconverter.com

Epoch timestamp: 1513654525
Timestamp in milliseconds: 1513654525000
Date and time (GMT): 2017년 December 19일 Tuesday AM 3:35:25
Date and time (your time zone): 2017년 12월 19일 화요일 오후 12:35:25 GMT+09:00

 

서버에서 보여주는 것이 Local 기준이라면

Epoch timestamp: 1513622125
Timestamp in milliseconds: 1513622125000
Date and time (GMT): 2017년 December 18일 Monday PM 6:35:25
Date and time (your time zone): 2017년 12월 19일 화요일 오전 3:35:25 GMT+09:00


이제 여기에 MSB/LSB 문제가


2025.01.10

영어로 비트코인 헤더 예제 구글링

https://developer.bitcoin.org/reference/block_chain.html

 

Block Chain — Bitcoin

This site aims to provide the docs you need to understand Bitcoin and start building Bitcoin-based applications.

developer.bitcoin.org

An example header in hex:

02000000 ........................... Block version: 2

b6ff0b1b1680a2862a30ca44d346d9e8
910d334beb48ca0c0000000000000000 ... Hash of previous block's header
9d10aa52ee949386ca9385695f04ede2
70dda20810decd12bc9b048aaab31471 ... Merkle root

24d95a54 ........................... [Unix time][unix epoch time]: 1415239972
30c31b18 ........................... Target: 0x1bc330 * 256**(0x18-3)
fe9f0864 ........................... Nonce

L->M 이면 멤버의 순서도 바꿔야 될 것 같다.

Web SHA256에 넣기위해 bit/little edian 코드를 물어봤다.

#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <string>

// 헥스 문자열을 바이트 배열로 변환하는 함수
std::string hexToBytes(const std::string& hex) {
    std::string bytes;
    bytes.reserve(hex.size() / 2);
    for (std::size_t i = 0; i < hex.size(); i += 2) {
        unsigned byte;
        std::istringstream hexByte(hex.substr(i, 2));
        hexByte >> std::hex >> byte;
        bytes.push_back(static_cast<char>(byte));
    }
    return bytes;
}

// 바이트 배열을 big endian으로 변환하는 함수
std::string toBigEndian(std::string& bytes) {
    std::reverse(bytes.begin(), bytes.end());
    return bytes;
}

// 바이트 배열을 헥스 문자열로 변환하는 함수
std::string bytesToHex(const std::string& bytes) {
    std::ostringstream hex;
    for (unsigned char byte : bytes) {
        hex << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(byte);
    }
    return hex.str();
}

int main() {
    std::string hexString = "0a1b2c3d";
    
    std::string bytes = hexToBytes(hexString);
    std::string bigEndianBytes = toBigEndian(bytes);
    std::string bigEndianHexString = bytesToHex(bigEndianBytes);
    
    std::cout << "Original Hex String: " << hexString << std::endl;
    std::cout << "Big Endian Hex String: " << bigEndianHexString << std::endl;
    
    return 0;
}

구글링 하다가 제대로 된 정보를 찾았다.

https://jusths.tistory.com/48

 

SHA-256 Bitcoin

SHA-256 씨리이즈 1. SHA-256 Hash Algorithm 2. SHA-256 프로세스 정리 3. SHA-256 By Hand - Message Expansion Function 4. SHA-256 By Hand - Round Function 5. SHA-256 Bitcoin - 참고링크: http://www.righto.com/2014/09/mining-bitcoin-with-pencil-an

jusths.tistory.com

Little Endian & Double SHA256 이 핵심 

Double SHA256 =  SHA256(SHA256(Header))

파트 Little Endian 으로 만들기
 바이트 순서 반대로
version 0x01000000
previous block hash 0xbddd99ccfda39da1b108ce1a5d70038d0a967bacb68b6b63065f626a00000000
merkle root 0x44f672226090d85db9a9f2fbfe5f0f9609b387af7be5b7fbb7a1767c831c9e99
time 0x5dbe6649

difficulty bits 0xffff001d
nonce 0x05e0ed6d
 값들로 계산될 해시값 0000000082b5015589a3fdf2d4baff403e6f0be035a5d9742c1cae6295464449

- https://www.unixtimestamp.com/

 

Unix Time Stamp - Epoch Converter

Epoch and unix timestamp converter for developers. Date and time function syntax reference for various programming languages.

www.unixtimestamp.com

 


위의 영문 싸이트에서의 예제도 테스트

02000000b6ff0b1b1680a2862a30ca44d346d9e8910d334beb48ca0c00000000000000009d10aa52ee949386ca9385695f04ede270dda20810decd12bc9b048aaab3147124d95a5430c31b18fe9f0864
=>
2837af674e81436b09e0c937e94d96fe32e5c872391ba1090000000000000000

2025.01.11

80Byte SHA256, 32Byte SHA256

//------------------------------------------------------------------------------
//First Stage
//------------------------------------------------------------------------------
for (int j=0; j<8; j++) {
	data_in[j] = SHA256_H0[j];
}

for (int j = 0; j < 64; j++) {
    imessage[j] = message[j];
}

for (int j = 0; j < 16; j++) {
   msg[j] = imessage[j*4+0] << 24 |
            imessage[j*4+1] << 16 |
            imessage[j*4+2] <<  8 |
            imessage[j*4+3] ;
}

	printf("----------------------------------------\n");
	printf("Message\n");
	for (int j=0; j<16; j++) {
		printf("%08x ", msg[j]);
		printf("\n");
	}
sha256_core(msg, data_in, data_tmp);
//------------------------------------------------------------------------------
//Second  (80-64 byte)
//------------------------------------------------------------------------------
for (int j = 0; j < 64; j++) {
    if (j<16) imessage[j] = message[j+64];
    else imessage[j]  = 0;
}

    imessage[16] = 0x80;

UINT len_bits = 80*8;
    imessage[64-4] = (len_bit >> 8*3) & 0xff;
    imessage[64-3] = (len_bit >> 8*2) & 0xff;
    imessage[64-2] = (len_bit >> 8*1) & 0xff;
    imessage[64-1] = (len_bit >> 8*0) & 0xff;

for (int j = 0; j < 16; j++) {
   msg[j] = imessage[j*4+0] << 24 |
            imessage[j*4+1] << 16 |
            imessage[j*4+2] <<  8 |
            imessage[j*4+3] ;
}

	printf("----------------------------------------\n");
	printf("Message\n");
	for (int j=0; j<16; j++) {
		printf("%08x ", msg[j]);
		printf("\n");
	}
sha256_core(msg, data_tmp, hash_first);


//------------------------------------------------------------------------------
//Double 
//------------------------------------------------------------------------------
for (int j=0; j<8; j++) {
	data_in[j] = SHA256_H0[j];
}

for (int j = 0; j < 16; j++) {
   if (j<8) msg[j] = hash_first[j];
   else     msg[j] = 0;
}
msg[8] = 0x80000000;
msg[15] = 32*8;

	printf("----------------------------------------\n");
	printf("Message\n");
	for (int j=0; j<16; j++) {
		printf("%08x ", msg[j]);
		printf("\n");
	}
sha256_core(msg, data_in, hash_second);

첫 SHA256은 80byte 이므로 2단계로 변환

두번째 SHA256은 첫번째 hash를 다시 변환 하므로 32 Byte 입력

 

'IT > 비트코인' 카테고리의 다른 글

[비트코인] Message & SHA256 정리  (0) 2025.02.04
[비트코인] KISA SHA256 테스트  (0) 2025.01.02
[비트코인] Python 채굴  (0) 2022.02.05

2025.01.02

KISA의 SHA256을 다시 테스트 하다보니 무언가 이상해서 다시 정리.

https://seed.kisa.or.kr/kisa/Board/21/detailView.do

 

gcc는 warnig,  g++ 로 컴파일 하면 에러 발생

invalid conversion from 'UINT* {aka unsigned int*}' to 'ULONG_PTR {aka long unsigned int*}' [-fpermissive]
typedef unsigned long ULONG;
typedef ULONG* ULONG_PTR;
void SHA256_Transform(ULONG_PTR Message, ULONG_PTR ChainVar)
        SHA256_Transform((ULONG_PTR)Info->szBuffer, Info->uChainVar);

 

SHA256_Encrpyt

  |- SHA256_Process

       |- SHA256_Transform

Pointer로 전달해야 되는데 typecasting이 안된 것 같다.

SHA256_Transform((ULONG_PTR)Info->szBuffer, (ULONG_PTR)Info->uChainVar);

 

그리고, SHA256 입력이 64Byte(512bit) 단위로 팩킹되고 마지막에 0x80 추가된다고 알고 있는데,

KISA코드에서는 Process.Transform 으로 한번 처리하고 Close.Transform에서 0x80관련 코드가 있다.

str(block_number) + transactions + previous_hash + str(nonce) => text
text + 8'b1000_0000 + 8'b0000_0000 * n + 64'b(text size [bit]) = message (512'b * m) -> SHA256

원래 알고 있던 개념으로 테스트하면 정상적으로 출력된다.

Initial hash value
 H[0] 6a09e667
 H[1] bb67ae85
 H[2] 3c6ef372
 H[3] a54ff53a
 H[4] 510e527f
 H[5] 9b05688c
 H[6] 1f83d9ab
 H[7] 5be0cd19
Input Message: "abc"
Digest: BA7816BF 8F01CFEA 414140DE 5DAE2223 B00361A3 96177A9C B410FF61 F20015AD

Input Message: "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
Digest: 248D6A61 D20638B8 E5C02693 0C3E6039 A33CE459 64FF2167 F6ECEDD4 19DB06C1

 

KISA 결과

int main(int argc, char* argv[])
{
    unsigned char i_d[1024]={0,};
    unsigned char o_d[32]={0,};
    string i_string = "abc";
    unsigned int len=0;
    len = i_string.length();
    for (int i=0;i<len;i++) i_d[i] = i_string[i];
    SHA256_Encrypt(i_d, len, o_d);
    cout << i_string << endl;
    for (int i=0;i<32;i++) printf("%02x", o_d[i]);
    return 0;
}
abc
8302f36526bc91ea7a9b15da985370bd477545ca25abd0c51eed56a3c560f074

https://csihyeon.tistory.com/46

 

sha256(hash algorithm)에 대해서 알아보자 (C++)

1) sha는 'Secure Hash Algorithm'의 약자고, 256은 메모리를 차지하는 비트 수이다. 2) 해시(16진법)의 길이는 언제나 64자이고 숫자뿐만 아니라 문자가 올 수 있다.sha256을 테스트해보고 싶으면 아래 사

csihyeon.tistory.com

zedwood 에서 받은 sha256으로 "abc" -> BA7816BF 8F01CFEA 414140DE 5DAE2223 B00361A3 96177A9C B410FF61 F20015AD

는 확인 되었는데

bitcoin 정보를 가지고 하면 블로그 결과와 다르다.


https://www.analyticsvidhya.com/blog/2021/05/how-to-mine-bitcoin-using-python-part-i/

 

How to mine Bitcoin using Python? ( Part - I )

Bitcoin ecosystem is made out of nodes or miners who execute the bitcoin code and store it in the blockchain. Lets mine bitcoin using python

www.analyticsvidhya.com

C++ 코드 영향일 수도 있으니 Python으로.


2024.01.03

https://emn178.github.io/online-tools/sha256.html

 

SHA256

This SHA256 online tool helps you calculate hashes from strings. You can input UTF-8, UTF-16, Hex, Base64, or other encodings. It also supports HMAC.

emn178.github.io

여기에서 테스트하니 정상

abc
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq
248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1

 

BitCoin Python 예제로 하면 비정상

684260
A->B->10
B->c->5
000000000000000000006bd3d6ef94d8a01de84e171d3553534783b128f06aad
36674

50b29f77f0b970646939619caa6b561b4f1d3418898089335a559875c30361fa

 

String을 어떻게 하느냐에 따라 결과가 다르다.

684260
A->B->10
B->c->5
000000000000000000006bd3d6ef94d8a01de84e171d3553534783b128f06aad36674

000086ae35230f32b08e9da254bd7ba1b351f11d40bde27a7ebd5e7ec9568f8d

 

C Code의 string에서도 줄바꿈 처리가 필요


string i_string = "684260\nA->B->10\nB->c->5\n000000000000000000006bd3d6ef94d8a01de84e171d3553534783b128f06aad36674";

수정된 KISA 코드에서는 정상 출력

'IT > 비트코인' 카테고리의 다른 글

[비트코인] Message & SHA256 정리  (0) 2025.02.04
[비트코인] SHA256 & 채굴 (최종?)  (0) 2025.01.09
[비트코인] Python 채굴  (0) 2022.02.05

2022.02.05

0. Ref.

https://www.youtube.com/watch?v=JM3j7uBKnt8 

 

https://www.analyticsvidhya.com/blog/2021/05/how-to-mine-bitcoin-using-python-part-i/

 

How to mine Bitcoin using Python? ( Part - I ) - Analytics Vidhya

Bitcoin ecosystem is made out of nodes or miners who execute the bitcoin code and store it in the blockchain. Lets mine bitcoin using python

www.analyticsvidhya.com

https://blog.naver.com/PostView.naver?blogId=kgu3405&logNo=222538295628 

 

[코인] 아두이노(AVR)를 이용한 코인 채굴 테스트 (feat. 두이노코인 Duino-Coin 채굴)

안녕하세요, 재미로 코인 채굴하는 멍짱입니다~! 오늘 실험 내용은 AVR을 이용한 채굴입니다. 최근 제가...

blog.naver.com

https://github.com/kairess/bitcoin-mining-wonri

 

GitHub - kairess/bitcoin-mining-wonri

Contribute to kairess/bitcoin-mining-wonri development by creating an account on GitHub.

github.com

https://m.blog.naver.com/scw0531/221124543277

 

[아두이노 - AES/SHA를 이용한 암호화 적용]

안녕하세요!! 이번 포스팅은 아두이노에서 AES, SHA를 적용하여 암호화를 하는 방법을 알아보겠습니...

blog.naver.com

C++

http://www.secmem.org/blog/2019/07/21/sha256/

https://seed.kisa.or.kr/kisa/Board/21/detailView.do

 

KISA 암호이용활성화 - 자료실 - 암호알고리즘 소스코드

한국인터넷진흥원(KISA)에서는 256비트 해시함수 SHA-256을 쉽게 활용할 수 있도록, 소스코드를 배포하고 있습니다. 언어 : C/C++, Java, ASP, JSP, PHP 다음글 2019-01-31 이전글 2019-01-31

seed.kisa.or.kr


str(block_number) + transactions + previous_hash + str(nonce) => text

text + 8'b1000_0000 + 8'b0000_0000 * n + 64'b(text size [bit]) = message (512'b * m) -> SHA256

const unsigned int H0[8] = {
                    0x6a09e667,
                    0xbb67ae85,
                    0x3c6ef372,
                    0xa54ff53a,
                    0x510e527f,
                    0x9b05688c,
                    0x1f83d9ab,
                    0x5be0cd19};
                    
const unsigned int SHA256_K[64] = 
{
	0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
	0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
	0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
	0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
	0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
	0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
	0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
	0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
	0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
	0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
	0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};

 

'IT > 비트코인' 카테고리의 다른 글

[비트코인] Message & SHA256 정리  (0) 2025.02.04
[비트코인] SHA256 & 채굴 (최종?)  (0) 2025.01.09
[비트코인] KISA SHA256 테스트  (0) 2025.01.02

+ Recent posts