diff --git a/main.py b/main.py index 33ff9d15..561371f9 100644 --- a/main.py +++ b/main.py @@ -288,14 +288,19 @@ def serialize_coinbase(transactions): inputs = transaction['vin'] outputs = transaction['vout'] - # Start building the transaction byte array tx_data = ( - varint_encode(len(inputs)) + little_endian_bytes(version, 4) ) + has_witness = any('witness' in vin for vin in inputs) + if has_witness : + tx_data += bytes.fromhex('00') + tx_data += bytes.fromhex('01') # Process each input + + tx_data += varint_encode(len(inputs)) for input in inputs: - txid = bytes.fromhex(input['txid'][::-1]) # Reverse txid for little-endian + txid = bytes.fromhex(input['txid'])[::-1] # Reverse txid for little-endian prev_tx_out_index = input['vout'] scriptsig = bytes.fromhex(input['scriptsig']) sequence = input['sequence'] @@ -323,25 +328,23 @@ def serialize_coinbase(transactions): varint_encode(len(script_pubkey)) + script_pubkey ) - # Append locktime - - # If transaction has witness data, append it before hashing - if any('witness' in vin for vin in inputs): + + if has_witness: for input in inputs: if 'witness' in input: + witness = input['witness'] + tx_data += varint_encode(len(witness)) for witness_item in input['witness']: - tx_data += bytes.fromhex('01') - tx_data += varint_encode(len(witness_item) // 2) # Length of witness item in bytes + tx_data += varint_encode(len(bytes.fromhex(witness_item))) # Length of witness item tx_data += bytes.fromhex(witness_item) - marker = bytes.fromhex('00') - flag = bytes.fromhex('01') - tx_data = marker + flag + tx_data # Add segwit marker and flag + + # Calculate wtxid (hash of tx_data with marker and flag) tx_data += little_endian_bytes(locktime, 4) - wtxid_data = little_endian_bytes(version, 4) + tx_data - wtxid_hash = hashlib.sha256(hashlib.sha256(wtxid_data).digest()).digest() + wtxid_hash = hashlib.sha256(hashlib.sha256(tx_data).digest()).digest() - return wtxid_data.hex(), wtxid_hash[::-1].hex() + + return tx_data.hex(), wtxid_hash[::-1].hex() def compute_witness_commitment(witness_root_hash): diff --git a/output.txt b/output.txt index f2abe350..9d2e6121 100644 --- a/output.txt +++ b/output.txt @@ -1,4 +1,4 @@ -000000040000000000000000000000000000000000000000000000000000000000000000392ae3d4938a9c9709af2440f2705a2ce8e84b32b9c22f186022a69b3cfb46ccb27e3166ffff001fd8040000 +000000040000000000000000000000000000000000000000000000000000000000000000392ae3d4938a9c9709af2440f2705a2ce8e84b32b9c22f186022a69b3cfb46ccaf7f3166ffff001f47100100 020000000001010000000000000000000000000000000000000000000000000000000000000000010000000d03951a0610076c0000946e0100000000000200000000000000001976a914acd783f632ad040fc72d9a06ec17ffb2d8a97a5d88ac0000000000000000266a24aa21a9ed4ae72437cf56c7f1b9fac29c8eaf84d56389121cb4fcddfb9f60bb732719f51e0120000000000000000000000000000000000000000000000000000000000000000000000000 8ec2128535e6b2c8279b7c73aae5cb8467e8ccae986ab0d9a771098f7834cfa3 25ce6b8d39d02471c43a804569a72015e81f3400170c1b8f5418e6938cd60b74