2 # Copyright (c) 2010 ArtForz -- public domain half-a-node
3 # Copyright (c) 2012 Jeff Garzik
4 # Copyright (c) 2010-2017 The Bitcoin Core developers
5 # Distributed under the MIT software license, see the accompanying
6 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 """Bitcoin test framework primitive and message strcutures
9 CBlock, CTransaction, CBlockHeader, CTxIn, CTxOut, etc....:
10 data structures that should map to corresponding structures in
13 msg_block, msg_tx, msg_headers, etc.:
14 data structures that represent network messages
16 ser_*, deser_*: functions that handle serialization/deserialization."""
17 from codecs
import encode
20 from io
import BytesIO
26 from test_framework
.siphash
import siphash256
27 from test_framework
.util
import hex_str_to_bytes
, bytes_to_hex_str
, wait_until
29 MIN_VERSION_SUPPORTED
= 60001
30 MY_VERSION
= 70014 # past bip-31 for ping/pong
31 MY_SUBVERSION
= b
"/python-mininode-tester:0.0.3/"
32 MY_RELAY
= 1 # from version 70001 onwards, fRelay should be appended to version messages (BIP37)
35 MAX_BLOCK_BASE_SIZE
= 1000000
37 COIN
= 100000000 # 1 btc in satoshis
39 NODE_NETWORK
= (1 << 0)
40 # NODE_GETUTXO = (1 << 1)
41 # NODE_BLOOM = (1 << 2)
42 NODE_WITNESS
= (1 << 3)
43 NODE_UNSUPPORTED_SERVICE_BIT_5
= (1 << 5)
44 NODE_UNSUPPORTED_SERVICE_BIT_7
= (1 << 7)
46 # Serialization/deserialization tools
48 return hashlib
.new('sha256', s
).digest()
51 return hashlib
.new('ripemd160', s
).digest()
54 return sha256(sha256(s
))
56 def ser_compact_size(l
):
59 r
= struct
.pack("B", l
)
61 r
= struct
.pack("<BH", 253, l
)
63 r
= struct
.pack("<BI", 254, l
)
65 r
= struct
.pack("<BQ", 255, l
)
68 def deser_compact_size(f
):
69 nit
= struct
.unpack("<B", f
.read(1))[0]
71 nit
= struct
.unpack("<H", f
.read(2))[0]
73 nit
= struct
.unpack("<I", f
.read(4))[0]
75 nit
= struct
.unpack("<Q", f
.read(8))[0]
79 nit
= deser_compact_size(f
)
83 return ser_compact_size(len(s
)) + s
88 t
= struct
.unpack("<I", f
.read(4))[0]
96 rs
+= struct
.pack("<I", u
& 0xFFFFFFFF)
101 def uint256_from_str(s
):
103 t
= struct
.unpack("<IIIIIIII", s
[:32])
105 r
+= t
[i
] << (i
* 32)
109 def uint256_from_compact(c
):
110 nbytes
= (c
>> 24) & 0xFF
111 v
= (c
& 0xFFFFFF) << (8 * (nbytes
- 3))
115 def deser_vector(f
, c
):
116 nit
= deser_compact_size(f
)
125 # ser_function_name: Allow for an alternate serialization function on the
126 # entries in the vector (we use this for serializing the vector of transactions
127 # for a witness block).
128 def ser_vector(l
, ser_function_name
=None):
129 r
= ser_compact_size(len(l
))
131 if ser_function_name
:
132 r
+= getattr(i
, ser_function_name
)()
138 def deser_uint256_vector(f
):
139 nit
= deser_compact_size(f
)
147 def ser_uint256_vector(l
):
148 r
= ser_compact_size(len(l
))
154 def deser_string_vector(f
):
155 nit
= deser_compact_size(f
)
163 def ser_string_vector(l
):
164 r
= ser_compact_size(len(l
))
170 # Deserialize from a hex string representation (eg from RPC)
171 def FromHex(obj
, hex_string
):
172 obj
.deserialize(BytesIO(hex_str_to_bytes(hex_string
)))
175 # Convert a binary-serializable object to hex (eg for submission via RPC)
177 return bytes_to_hex_str(obj
.serialize())
179 # Objects that map to bitcoind objects, which can be serialized/deserialized
184 self
.pchReserved
= b
"\x00" * 10 + b
"\xff" * 2
188 def deserialize(self
, f
):
189 self
.nServices
= struct
.unpack("<Q", f
.read(8))[0]
190 self
.pchReserved
= f
.read(12)
191 self
.ip
= socket
.inet_ntoa(f
.read(4))
192 self
.port
= struct
.unpack(">H", f
.read(2))[0]
196 r
+= struct
.pack("<Q", self
.nServices
)
197 r
+= self
.pchReserved
198 r
+= socket
.inet_aton(self
.ip
)
199 r
+= struct
.pack(">H", self
.port
)
203 return "CAddress(nServices=%i ip=%s port=%i)" % (self
.nServices
,
206 MSG_WITNESS_FLAG
= 1<<30
213 1|MSG_WITNESS_FLAG
: "WitnessTx",
214 2|MSG_WITNESS_FLAG
: "WitnessBlock",
218 def __init__(self
, t
=0, h
=0):
222 def deserialize(self
, f
):
223 self
.type = struct
.unpack("<i", f
.read(4))[0]
224 self
.hash = deser_uint256(f
)
228 r
+= struct
.pack("<i", self
.type)
229 r
+= ser_uint256(self
.hash)
233 return "CInv(type=%s hash=%064x)" \
234 % (self
.typemap
[self
.type], self
.hash)
237 class CBlockLocator():
239 self
.nVersion
= MY_VERSION
242 def deserialize(self
, f
):
243 self
.nVersion
= struct
.unpack("<i", f
.read(4))[0]
244 self
.vHave
= deser_uint256_vector(f
)
248 r
+= struct
.pack("<i", self
.nVersion
)
249 r
+= ser_uint256_vector(self
.vHave
)
253 return "CBlockLocator(nVersion=%i vHave=%s)" \
254 % (self
.nVersion
, repr(self
.vHave
))
258 def __init__(self
, hash=0, n
=0):
262 def deserialize(self
, f
):
263 self
.hash = deser_uint256(f
)
264 self
.n
= struct
.unpack("<I", f
.read(4))[0]
268 r
+= ser_uint256(self
.hash)
269 r
+= struct
.pack("<I", self
.n
)
273 return "COutPoint(hash=%064x n=%i)" % (self
.hash, self
.n
)
277 def __init__(self
, outpoint
=None, scriptSig
=b
"", nSequence
=0):
279 self
.prevout
= COutPoint()
281 self
.prevout
= outpoint
282 self
.scriptSig
= scriptSig
283 self
.nSequence
= nSequence
285 def deserialize(self
, f
):
286 self
.prevout
= COutPoint()
287 self
.prevout
.deserialize(f
)
288 self
.scriptSig
= deser_string(f
)
289 self
.nSequence
= struct
.unpack("<I", f
.read(4))[0]
293 r
+= self
.prevout
.serialize()
294 r
+= ser_string(self
.scriptSig
)
295 r
+= struct
.pack("<I", self
.nSequence
)
299 return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" \
300 % (repr(self
.prevout
), bytes_to_hex_str(self
.scriptSig
),
305 def __init__(self
, nValue
=0, scriptPubKey
=b
""):
307 self
.scriptPubKey
= scriptPubKey
309 def deserialize(self
, f
):
310 self
.nValue
= struct
.unpack("<q", f
.read(8))[0]
311 self
.scriptPubKey
= deser_string(f
)
315 r
+= struct
.pack("<q", self
.nValue
)
316 r
+= ser_string(self
.scriptPubKey
)
320 return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \
321 % (self
.nValue
// COIN
, self
.nValue
% COIN
,
322 bytes_to_hex_str(self
.scriptPubKey
))
325 class CScriptWitness():
327 # stack is a vector of strings
331 return "CScriptWitness(%s)" % \
332 (",".join([bytes_to_hex_str(x
) for x
in self
.stack
]))
340 class CTxInWitness():
342 self
.scriptWitness
= CScriptWitness()
344 def deserialize(self
, f
):
345 self
.scriptWitness
.stack
= deser_string_vector(f
)
348 return ser_string_vector(self
.scriptWitness
.stack
)
351 return repr(self
.scriptWitness
)
354 return self
.scriptWitness
.is_null()
361 def deserialize(self
, f
):
362 for i
in range(len(self
.vtxinwit
)):
363 self
.vtxinwit
[i
].deserialize(f
)
367 # This is different than the usual vector serialization --
368 # we omit the length of the vector, which is required to be
369 # the same length as the transaction's vin vector.
370 for x
in self
.vtxinwit
:
375 return "CTxWitness(%s)" % \
376 (';'.join([repr(x
) for x
in self
.vtxinwit
]))
379 for x
in self
.vtxinwit
:
385 class CTransaction():
386 def __init__(self
, tx
=None):
391 self
.wit
= CTxWitness()
396 self
.nVersion
= tx
.nVersion
397 self
.vin
= copy
.deepcopy(tx
.vin
)
398 self
.vout
= copy
.deepcopy(tx
.vout
)
399 self
.nLockTime
= tx
.nLockTime
400 self
.sha256
= tx
.sha256
402 self
.wit
= copy
.deepcopy(tx
.wit
)
404 def deserialize(self
, f
):
405 self
.nVersion
= struct
.unpack("<i", f
.read(4))[0]
406 self
.vin
= deser_vector(f
, CTxIn
)
408 if len(self
.vin
) == 0:
409 flags
= struct
.unpack("<B", f
.read(1))[0]
410 # Not sure why flags can't be zero, but this
411 # matches the implementation in bitcoind
413 self
.vin
= deser_vector(f
, CTxIn
)
414 self
.vout
= deser_vector(f
, CTxOut
)
416 self
.vout
= deser_vector(f
, CTxOut
)
418 self
.wit
.vtxinwit
= [CTxInWitness() for i
in range(len(self
.vin
))]
419 self
.wit
.deserialize(f
)
420 self
.nLockTime
= struct
.unpack("<I", f
.read(4))[0]
424 def serialize_without_witness(self
):
426 r
+= struct
.pack("<i", self
.nVersion
)
427 r
+= ser_vector(self
.vin
)
428 r
+= ser_vector(self
.vout
)
429 r
+= struct
.pack("<I", self
.nLockTime
)
432 # Only serialize with witness when explicitly called for
433 def serialize_with_witness(self
):
435 if not self
.wit
.is_null():
438 r
+= struct
.pack("<i", self
.nVersion
)
441 r
+= ser_vector(dummy
)
442 r
+= struct
.pack("<B", flags
)
443 r
+= ser_vector(self
.vin
)
444 r
+= ser_vector(self
.vout
)
446 if (len(self
.wit
.vtxinwit
) != len(self
.vin
)):
447 # vtxinwit must have the same length as vin
448 self
.wit
.vtxinwit
= self
.wit
.vtxinwit
[:len(self
.vin
)]
449 for i
in range(len(self
.wit
.vtxinwit
), len(self
.vin
)):
450 self
.wit
.vtxinwit
.append(CTxInWitness())
451 r
+= self
.wit
.serialize()
452 r
+= struct
.pack("<I", self
.nLockTime
)
455 # Regular serialization is without witness -- must explicitly
456 # call serialize_with_witness to include witness data.
458 return self
.serialize_without_witness()
460 # Recalculate the txid (transaction hash without witness)
465 # We will only cache the serialization without witness in
466 # self.sha256 and self.hash -- those are expected to be the txid.
467 def calc_sha256(self
, with_witness
=False):
469 # Don't cache the result, just return it
470 return uint256_from_str(hash256(self
.serialize_with_witness()))
472 if self
.sha256
is None:
473 self
.sha256
= uint256_from_str(hash256(self
.serialize_without_witness()))
474 self
.hash = encode(hash256(self
.serialize())[::-1], 'hex_codec').decode('ascii')
478 for tout
in self
.vout
:
479 if tout
.nValue
< 0 or tout
.nValue
> 21000000 * COIN
:
484 return "CTransaction(nVersion=%i vin=%s vout=%s wit=%s nLockTime=%i)" \
485 % (self
.nVersion
, repr(self
.vin
), repr(self
.vout
), repr(self
.wit
), self
.nLockTime
)
488 class CBlockHeader():
489 def __init__(self
, header
=None):
493 self
.nVersion
= header
.nVersion
494 self
.hashPrevBlock
= header
.hashPrevBlock
495 self
.hashMerkleRoot
= header
.hashMerkleRoot
496 self
.nTime
= header
.nTime
497 self
.nBits
= header
.nBits
498 self
.nNonce
= header
.nNonce
499 self
.sha256
= header
.sha256
500 self
.hash = header
.hash
505 self
.hashPrevBlock
= 0
506 self
.hashMerkleRoot
= 0
513 def deserialize(self
, f
):
514 self
.nVersion
= struct
.unpack("<i", f
.read(4))[0]
515 self
.hashPrevBlock
= deser_uint256(f
)
516 self
.hashMerkleRoot
= deser_uint256(f
)
517 self
.nTime
= struct
.unpack("<I", f
.read(4))[0]
518 self
.nBits
= struct
.unpack("<I", f
.read(4))[0]
519 self
.nNonce
= struct
.unpack("<I", f
.read(4))[0]
525 r
+= struct
.pack("<i", self
.nVersion
)
526 r
+= ser_uint256(self
.hashPrevBlock
)
527 r
+= ser_uint256(self
.hashMerkleRoot
)
528 r
+= struct
.pack("<I", self
.nTime
)
529 r
+= struct
.pack("<I", self
.nBits
)
530 r
+= struct
.pack("<I", self
.nNonce
)
533 def calc_sha256(self
):
534 if self
.sha256
is None:
536 r
+= struct
.pack("<i", self
.nVersion
)
537 r
+= ser_uint256(self
.hashPrevBlock
)
538 r
+= ser_uint256(self
.hashMerkleRoot
)
539 r
+= struct
.pack("<I", self
.nTime
)
540 r
+= struct
.pack("<I", self
.nBits
)
541 r
+= struct
.pack("<I", self
.nNonce
)
542 self
.sha256
= uint256_from_str(hash256(r
))
543 self
.hash = encode(hash256(r
)[::-1], 'hex_codec').decode('ascii')
551 return "CBlockHeader(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x)" \
552 % (self
.nVersion
, self
.hashPrevBlock
, self
.hashMerkleRoot
,
553 time
.ctime(self
.nTime
), self
.nBits
, self
.nNonce
)
556 class CBlock(CBlockHeader
):
557 def __init__(self
, header
=None):
558 super(CBlock
, self
).__init
__(header
)
561 def deserialize(self
, f
):
562 super(CBlock
, self
).deserialize(f
)
563 self
.vtx
= deser_vector(f
, CTransaction
)
565 def serialize(self
, with_witness
=False):
567 r
+= super(CBlock
, self
).serialize()
569 r
+= ser_vector(self
.vtx
, "serialize_with_witness")
571 r
+= ser_vector(self
.vtx
)
574 # Calculate the merkle root given a vector of transaction hashes
576 def get_merkle_root(cls
, hashes
):
577 while len(hashes
) > 1:
579 for i
in range(0, len(hashes
), 2):
580 i2
= min(i
+1, len(hashes
)-1)
581 newhashes
.append(hash256(hashes
[i
] + hashes
[i2
]))
583 return uint256_from_str(hashes
[0])
585 def calc_merkle_root(self
):
589 hashes
.append(ser_uint256(tx
.sha256
))
590 return self
.get_merkle_root(hashes
)
592 def calc_witness_merkle_root(self
):
593 # For witness root purposes, the hash of the
594 # coinbase, with witness, is defined to be 0...0
595 hashes
= [ser_uint256(0)]
597 for tx
in self
.vtx
[1:]:
598 # Calculate the hashes with witness data
599 hashes
.append(ser_uint256(tx
.calc_sha256(True)))
601 return self
.get_merkle_root(hashes
)
605 target
= uint256_from_compact(self
.nBits
)
606 if self
.sha256
> target
:
609 if not tx
.is_valid():
611 if self
.calc_merkle_root() != self
.hashMerkleRoot
:
617 target
= uint256_from_compact(self
.nBits
)
618 while self
.sha256
> target
:
623 return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x vtx=%s)" \
624 % (self
.nVersion
, self
.hashPrevBlock
, self
.hashMerkleRoot
,
625 time
.ctime(self
.nTime
), self
.nBits
, self
.nNonce
, repr(self
.vtx
))
628 class PrefilledTransaction():
629 def __init__(self
, index
=0, tx
= None):
633 def deserialize(self
, f
):
634 self
.index
= deser_compact_size(f
)
635 self
.tx
= CTransaction()
636 self
.tx
.deserialize(f
)
638 def serialize(self
, with_witness
=False):
640 r
+= ser_compact_size(self
.index
)
642 r
+= self
.tx
.serialize_with_witness()
644 r
+= self
.tx
.serialize_without_witness()
647 def serialize_with_witness(self
):
648 return self
.serialize(with_witness
=True)
651 return "PrefilledTransaction(index=%d, tx=%s)" % (self
.index
, repr(self
.tx
))
653 # This is what we send on the wire, in a cmpctblock message.
654 class P2PHeaderAndShortIDs():
656 self
.header
= CBlockHeader()
658 self
.shortids_length
= 0
660 self
.prefilled_txn_length
= 0
661 self
.prefilled_txn
= []
663 def deserialize(self
, f
):
664 self
.header
.deserialize(f
)
665 self
.nonce
= struct
.unpack("<Q", f
.read(8))[0]
666 self
.shortids_length
= deser_compact_size(f
)
667 for i
in range(self
.shortids_length
):
668 # shortids are defined to be 6 bytes in the spec, so append
669 # two zero bytes and read it in as an 8-byte number
670 self
.shortids
.append(struct
.unpack("<Q", f
.read(6) + b
'\x00\x00')[0])
671 self
.prefilled_txn
= deser_vector(f
, PrefilledTransaction
)
672 self
.prefilled_txn_length
= len(self
.prefilled_txn
)
674 # When using version 2 compact blocks, we must serialize with_witness.
675 def serialize(self
, with_witness
=False):
677 r
+= self
.header
.serialize()
678 r
+= struct
.pack("<Q", self
.nonce
)
679 r
+= ser_compact_size(self
.shortids_length
)
680 for x
in self
.shortids
:
681 # We only want the first 6 bytes
682 r
+= struct
.pack("<Q", x
)[0:6]
684 r
+= ser_vector(self
.prefilled_txn
, "serialize_with_witness")
686 r
+= ser_vector(self
.prefilled_txn
)
690 return "P2PHeaderAndShortIDs(header=%s, nonce=%d, shortids_length=%d, shortids=%s, prefilled_txn_length=%d, prefilledtxn=%s" % (repr(self
.header
), self
.nonce
, self
.shortids_length
, repr(self
.shortids
), self
.prefilled_txn_length
, repr(self
.prefilled_txn
))
692 # P2P version of the above that will use witness serialization (for compact
694 class P2PHeaderAndShortWitnessIDs(P2PHeaderAndShortIDs
):
696 return super(P2PHeaderAndShortWitnessIDs
, self
).serialize(with_witness
=True)
698 # Calculate the BIP 152-compact blocks shortid for a given transaction hash
699 def calculate_shortid(k0
, k1
, tx_hash
):
700 expected_shortid
= siphash256(k0
, k1
, tx_hash
)
701 expected_shortid
&= 0x0000ffffffffffff
702 return expected_shortid
704 # This version gets rid of the array lengths, and reinterprets the differential
705 # encoding into indices that can be used for lookup.
706 class HeaderAndShortIDs():
707 def __init__(self
, p2pheaders_and_shortids
= None):
708 self
.header
= CBlockHeader()
711 self
.prefilled_txn
= []
712 self
.use_witness
= False
714 if p2pheaders_and_shortids
!= None:
715 self
.header
= p2pheaders_and_shortids
.header
716 self
.nonce
= p2pheaders_and_shortids
.nonce
717 self
.shortids
= p2pheaders_and_shortids
.shortids
719 for x
in p2pheaders_and_shortids
.prefilled_txn
:
720 self
.prefilled_txn
.append(PrefilledTransaction(x
.index
+ last_index
+ 1, x
.tx
))
721 last_index
= self
.prefilled_txn
[-1].index
725 ret
= P2PHeaderAndShortWitnessIDs()
727 ret
= P2PHeaderAndShortIDs()
728 ret
.header
= self
.header
729 ret
.nonce
= self
.nonce
730 ret
.shortids_length
= len(self
.shortids
)
731 ret
.shortids
= self
.shortids
732 ret
.prefilled_txn_length
= len(self
.prefilled_txn
)
733 ret
.prefilled_txn
= []
735 for x
in self
.prefilled_txn
:
736 ret
.prefilled_txn
.append(PrefilledTransaction(x
.index
- last_index
- 1, x
.tx
))
740 def get_siphash_keys(self
):
741 header_nonce
= self
.header
.serialize()
742 header_nonce
+= struct
.pack("<Q", self
.nonce
)
743 hash_header_nonce_as_str
= sha256(header_nonce
)
744 key0
= struct
.unpack("<Q", hash_header_nonce_as_str
[0:8])[0]
745 key1
= struct
.unpack("<Q", hash_header_nonce_as_str
[8:16])[0]
746 return [ key0
, key1
]
748 # Version 2 compact blocks use wtxid in shortids (rather than txid)
749 def initialize_from_block(self
, block
, nonce
=0, prefill_list
= [0], use_witness
= False):
750 self
.header
= CBlockHeader(block
)
752 self
.prefilled_txn
= [ PrefilledTransaction(i
, block
.vtx
[i
]) for i
in prefill_list
]
754 self
.use_witness
= use_witness
755 [k0
, k1
] = self
.get_siphash_keys()
756 for i
in range(len(block
.vtx
)):
757 if i
not in prefill_list
:
758 tx_hash
= block
.vtx
[i
].sha256
760 tx_hash
= block
.vtx
[i
].calc_sha256(with_witness
=True)
761 self
.shortids
.append(calculate_shortid(k0
, k1
, tx_hash
))
764 return "HeaderAndShortIDs(header=%s, nonce=%d, shortids=%s, prefilledtxn=%s" % (repr(self
.header
), self
.nonce
, repr(self
.shortids
), repr(self
.prefilled_txn
))
767 class BlockTransactionsRequest():
769 def __init__(self
, blockhash
=0, indexes
= None):
770 self
.blockhash
= blockhash
771 self
.indexes
= indexes
if indexes
!= None else []
773 def deserialize(self
, f
):
774 self
.blockhash
= deser_uint256(f
)
775 indexes_length
= deser_compact_size(f
)
776 for i
in range(indexes_length
):
777 self
.indexes
.append(deser_compact_size(f
))
781 r
+= ser_uint256(self
.blockhash
)
782 r
+= ser_compact_size(len(self
.indexes
))
783 for x
in self
.indexes
:
784 r
+= ser_compact_size(x
)
787 # helper to set the differentially encoded indexes from absolute ones
788 def from_absolute(self
, absolute_indexes
):
791 for x
in absolute_indexes
:
792 self
.indexes
.append(x
-last_index
-1)
795 def to_absolute(self
):
796 absolute_indexes
= []
798 for x
in self
.indexes
:
799 absolute_indexes
.append(x
+last_index
+1)
800 last_index
= absolute_indexes
[-1]
801 return absolute_indexes
804 return "BlockTransactionsRequest(hash=%064x indexes=%s)" % (self
.blockhash
, repr(self
.indexes
))
807 class BlockTransactions():
809 def __init__(self
, blockhash
=0, transactions
= None):
810 self
.blockhash
= blockhash
811 self
.transactions
= transactions
if transactions
!= None else []
813 def deserialize(self
, f
):
814 self
.blockhash
= deser_uint256(f
)
815 self
.transactions
= deser_vector(f
, CTransaction
)
817 def serialize(self
, with_witness
=False):
819 r
+= ser_uint256(self
.blockhash
)
821 r
+= ser_vector(self
.transactions
, "serialize_with_witness")
823 r
+= ser_vector(self
.transactions
)
827 return "BlockTransactions(hash=%064x transactions=%s)" % (self
.blockhash
, repr(self
.transactions
))
830 # Objects that correspond to messages on the wire
835 self
.nVersion
= MY_VERSION
836 self
.nServices
= NODE_NETWORK | NODE_WITNESS
837 self
.nTime
= int(time
.time())
838 self
.addrTo
= CAddress()
839 self
.addrFrom
= CAddress()
840 self
.nNonce
= random
.getrandbits(64)
841 self
.strSubVer
= MY_SUBVERSION
842 self
.nStartingHeight
= -1
843 self
.nRelay
= MY_RELAY
845 def deserialize(self
, f
):
846 self
.nVersion
= struct
.unpack("<i", f
.read(4))[0]
847 if self
.nVersion
== 10300:
849 self
.nServices
= struct
.unpack("<Q", f
.read(8))[0]
850 self
.nTime
= struct
.unpack("<q", f
.read(8))[0]
851 self
.addrTo
= CAddress()
852 self
.addrTo
.deserialize(f
)
854 if self
.nVersion
>= 106:
855 self
.addrFrom
= CAddress()
856 self
.addrFrom
.deserialize(f
)
857 self
.nNonce
= struct
.unpack("<Q", f
.read(8))[0]
858 self
.strSubVer
= deser_string(f
)
862 self
.strSubVer
= None
863 self
.nStartingHeight
= None
865 if self
.nVersion
>= 209:
866 self
.nStartingHeight
= struct
.unpack("<i", f
.read(4))[0]
868 self
.nStartingHeight
= None
870 if self
.nVersion
>= 70001:
871 # Relay field is optional for version 70001 onwards
873 self
.nRelay
= struct
.unpack("<b", f
.read(1))[0]
881 r
+= struct
.pack("<i", self
.nVersion
)
882 r
+= struct
.pack("<Q", self
.nServices
)
883 r
+= struct
.pack("<q", self
.nTime
)
884 r
+= self
.addrTo
.serialize()
885 r
+= self
.addrFrom
.serialize()
886 r
+= struct
.pack("<Q", self
.nNonce
)
887 r
+= ser_string(self
.strSubVer
)
888 r
+= struct
.pack("<i", self
.nStartingHeight
)
889 r
+= struct
.pack("<b", self
.nRelay
)
893 return 'msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i nRelay=%i)' \
894 % (self
.nVersion
, self
.nServices
, time
.ctime(self
.nTime
),
895 repr(self
.addrTo
), repr(self
.addrFrom
), self
.nNonce
,
896 self
.strSubVer
, self
.nStartingHeight
, self
.nRelay
)
905 def deserialize(self
, f
):
912 return "msg_verack()"
921 def deserialize(self
, f
):
922 self
.addrs
= deser_vector(f
, CAddress
)
925 return ser_vector(self
.addrs
)
928 return "msg_addr(addrs=%s)" % (repr(self
.addrs
))
934 def __init__(self
, inv
=None):
940 def deserialize(self
, f
):
941 self
.inv
= deser_vector(f
, CInv
)
944 return ser_vector(self
.inv
)
947 return "msg_inv(inv=%s)" % (repr(self
.inv
))
953 def __init__(self
, inv
=None):
954 self
.inv
= inv
if inv
!= None else []
956 def deserialize(self
, f
):
957 self
.inv
= deser_vector(f
, CInv
)
960 return ser_vector(self
.inv
)
963 return "msg_getdata(inv=%s)" % (repr(self
.inv
))
966 class msg_getblocks():
967 command
= b
"getblocks"
970 self
.locator
= CBlockLocator()
973 def deserialize(self
, f
):
974 self
.locator
= CBlockLocator()
975 self
.locator
.deserialize(f
)
976 self
.hashstop
= deser_uint256(f
)
980 r
+= self
.locator
.serialize()
981 r
+= ser_uint256(self
.hashstop
)
985 return "msg_getblocks(locator=%s hashstop=%064x)" \
986 % (repr(self
.locator
), self
.hashstop
)
992 def __init__(self
, tx
=CTransaction()):
995 def deserialize(self
, f
):
996 self
.tx
.deserialize(f
)
999 return self
.tx
.serialize_without_witness()
1002 return "msg_tx(tx=%s)" % (repr(self
.tx
))
1004 class msg_witness_tx(msg_tx
):
1006 def serialize(self
):
1007 return self
.tx
.serialize_with_witness()
1013 def __init__(self
, block
=None):
1015 self
.block
= CBlock()
1019 def deserialize(self
, f
):
1020 self
.block
.deserialize(f
)
1022 def serialize(self
):
1023 return self
.block
.serialize()
1026 return "msg_block(block=%s)" % (repr(self
.block
))
1028 # for cases where a user needs tighter control over what is sent over the wire
1029 # note that the user must supply the name of the command, and the data
1030 class msg_generic():
1031 def __init__(self
, command
, data
=None):
1032 self
.command
= command
1035 def serialize(self
):
1039 return "msg_generic()"
1041 class msg_witness_block(msg_block
):
1043 def serialize(self
):
1044 r
= self
.block
.serialize(with_witness
=True)
1047 class msg_getaddr():
1048 command
= b
"getaddr"
1053 def deserialize(self
, f
):
1056 def serialize(self
):
1060 return "msg_getaddr()"
1066 def __init__(self
, nonce
=0):
1069 def deserialize(self
, f
):
1070 self
.nonce
= struct
.unpack("<Q", f
.read(8))[0]
1072 def serialize(self
):
1074 r
+= struct
.pack("<Q", self
.nonce
)
1078 return "msg_ping(nonce=%08x)" % self
.nonce
1084 def __init__(self
, nonce
=0):
1087 def deserialize(self
, f
):
1088 self
.nonce
= struct
.unpack("<Q", f
.read(8))[0]
1090 def serialize(self
):
1092 r
+= struct
.pack("<Q", self
.nonce
)
1096 return "msg_pong(nonce=%08x)" % self
.nonce
1099 class msg_mempool():
1100 command
= b
"mempool"
1105 def deserialize(self
, f
):
1108 def serialize(self
):
1112 return "msg_mempool()"
1114 class msg_sendheaders():
1115 command
= b
"sendheaders"
1120 def deserialize(self
, f
):
1123 def serialize(self
):
1127 return "msg_sendheaders()"
1130 # getheaders message has
1133 # hash_stop (hash of last desired block header, 0 to get as many as possible)
1134 class msg_getheaders():
1135 command
= b
"getheaders"
1138 self
.locator
= CBlockLocator()
1141 def deserialize(self
, f
):
1142 self
.locator
= CBlockLocator()
1143 self
.locator
.deserialize(f
)
1144 self
.hashstop
= deser_uint256(f
)
1146 def serialize(self
):
1148 r
+= self
.locator
.serialize()
1149 r
+= ser_uint256(self
.hashstop
)
1153 return "msg_getheaders(locator=%s, stop=%064x)" \
1154 % (repr(self
.locator
), self
.hashstop
)
1157 # headers message has
1158 # <count> <vector of block headers>
1159 class msg_headers():
1160 command
= b
"headers"
1162 def __init__(self
, headers
=None):
1163 self
.headers
= headers
if headers
is not None else []
1165 def deserialize(self
, f
):
1166 # comment in bitcoind indicates these should be deserialized as blocks
1167 blocks
= deser_vector(f
, CBlock
)
1169 self
.headers
.append(CBlockHeader(x
))
1171 def serialize(self
):
1172 blocks
= [CBlock(x
) for x
in self
.headers
]
1173 return ser_vector(blocks
)
1176 return "msg_headers(headers=%s)" % repr(self
.headers
)
1181 REJECT_MALFORMED
= 1
1189 def deserialize(self
, f
):
1190 self
.message
= deser_string(f
)
1191 self
.code
= struct
.unpack("<B", f
.read(1))[0]
1192 self
.reason
= deser_string(f
)
1193 if (self
.code
!= self
.REJECT_MALFORMED
and
1194 (self
.message
== b
"block" or self
.message
== b
"tx")):
1195 self
.data
= deser_uint256(f
)
1197 def serialize(self
):
1198 r
= ser_string(self
.message
)
1199 r
+= struct
.pack("<B", self
.code
)
1200 r
+= ser_string(self
.reason
)
1201 if (self
.code
!= self
.REJECT_MALFORMED
and
1202 (self
.message
== b
"block" or self
.message
== b
"tx")):
1203 r
+= ser_uint256(self
.data
)
1207 return "msg_reject: %s %d %s [%064x]" \
1208 % (self
.message
, self
.code
, self
.reason
, self
.data
)
1210 class msg_feefilter():
1211 command
= b
"feefilter"
1213 def __init__(self
, feerate
=0):
1214 self
.feerate
= feerate
1216 def deserialize(self
, f
):
1217 self
.feerate
= struct
.unpack("<Q", f
.read(8))[0]
1219 def serialize(self
):
1221 r
+= struct
.pack("<Q", self
.feerate
)
1225 return "msg_feefilter(feerate=%08x)" % self
.feerate
1227 class msg_sendcmpct():
1228 command
= b
"sendcmpct"
1231 self
.announce
= False
1234 def deserialize(self
, f
):
1235 self
.announce
= struct
.unpack("<?", f
.read(1))[0]
1236 self
.version
= struct
.unpack("<Q", f
.read(8))[0]
1238 def serialize(self
):
1240 r
+= struct
.pack("<?", self
.announce
)
1241 r
+= struct
.pack("<Q", self
.version
)
1245 return "msg_sendcmpct(announce=%s, version=%lu)" % (self
.announce
, self
.version
)
1247 class msg_cmpctblock():
1248 command
= b
"cmpctblock"
1250 def __init__(self
, header_and_shortids
= None):
1251 self
.header_and_shortids
= header_and_shortids
1253 def deserialize(self
, f
):
1254 self
.header_and_shortids
= P2PHeaderAndShortIDs()
1255 self
.header_and_shortids
.deserialize(f
)
1257 def serialize(self
):
1259 r
+= self
.header_and_shortids
.serialize()
1263 return "msg_cmpctblock(HeaderAndShortIDs=%s)" % repr(self
.header_and_shortids
)
1265 class msg_getblocktxn():
1266 command
= b
"getblocktxn"
1269 self
.block_txn_request
= None
1271 def deserialize(self
, f
):
1272 self
.block_txn_request
= BlockTransactionsRequest()
1273 self
.block_txn_request
.deserialize(f
)
1275 def serialize(self
):
1277 r
+= self
.block_txn_request
.serialize()
1281 return "msg_getblocktxn(block_txn_request=%s)" % (repr(self
.block_txn_request
))
1283 class msg_blocktxn():
1284 command
= b
"blocktxn"
1287 self
.block_transactions
= BlockTransactions()
1289 def deserialize(self
, f
):
1290 self
.block_transactions
.deserialize(f
)
1292 def serialize(self
):
1294 r
+= self
.block_transactions
.serialize()
1298 return "msg_blocktxn(block_transactions=%s)" % (repr(self
.block_transactions
))
1300 class msg_witness_blocktxn(msg_blocktxn
):
1301 def serialize(self
):
1303 r
+= self
.block_transactions
.serialize(with_witness
=True)