38
38
MAX_INV_SZ = 50000
39
39
MAX_BLOCK_SIZE = 1000000
40
40
41
+ NODE_NETWORK = (1 << 0 )
42
+ NODE_GETUTXO = (1 << 1 )
43
+ NODE_BLOOM = (1 << 2 )
44
+ NODE_WITNESS = (1 << 3 )
45
+
41
46
# Keep our own socket map for asyncore, so that we can track disconnects
42
47
# ourselves (to workaround an issue with closing an asyncore socket when
43
48
# using select)
@@ -127,7 +132,10 @@ def deser_vector(f, c):
127
132
return r
128
133
129
134
130
- def ser_vector (l ):
135
+ # ser_function_name: Allow for an alternate serialization function on the
136
+ # entries in the vector (we use this for serializing the vector of transactions
137
+ # for a witness block).
138
+ def ser_vector (l , ser_function_name = None ):
131
139
r = ""
132
140
if len (l ) < 253 :
133
141
r = chr (len (l ))
@@ -138,7 +146,10 @@ def ser_vector(l):
138
146
else :
139
147
r = chr (255 ) + struct .pack ("<Q" , len (l ))
140
148
for i in l :
141
- r += i .serialize ()
149
+ if ser_function_name :
150
+ r += getattr (i , ser_function_name )()
151
+ else :
152
+ r += i .serialize ()
142
153
return r
143
154
144
155
@@ -267,12 +278,16 @@ def __repr__(self):
267
278
return "CAddress(nServices=%i ip=%s port=%i)" % (self .nServices ,
268
279
self .ip , self .port )
269
280
281
+ MSG_WITNESS_FLAG = 1 << 30
270
282
271
283
class CInv (object ):
272
284
typemap = {
273
285
0 : "Error" ,
274
286
1 : "TX" ,
275
- 2 : "Block" }
287
+ 2 : "Block" ,
288
+ 1 | MSG_WITNESS_FLAG : "WitnessTx" ,
289
+ 2 | MSG_WITNESS_FLAG : "WitnessBlock"
290
+ }
276
291
277
292
def __init__ (self , t = 0 , h = 0L ):
278
293
self .type = t
@@ -381,12 +396,73 @@ def __repr__(self):
381
396
binascii .hexlify (self .scriptPubKey ))
382
397
383
398
399
+ class CScriptWitness (object ):
400
+ def __init__ (self ):
401
+ # stack is a vector of strings
402
+ self .stack = []
403
+
404
+ def __repr__ (self ):
405
+ return "CScriptWitness(%s)" % \
406
+ ("," .join ([binascii .hexlify (x ) for x in self .stack ]))
407
+
408
+ def is_null (self ):
409
+ if self .stack :
410
+ return False
411
+ return True
412
+
413
+
414
+ class CTxinWitness (object ):
415
+ def __init__ (self ):
416
+ self .scriptWitness = CScriptWitness ()
417
+
418
+ def deserialize (self , f ):
419
+ self .scriptWitness .stack = deser_string_vector (f )
420
+
421
+ def serialize (self ):
422
+ return ser_string_vector (self .scriptWitness .stack )
423
+
424
+ def __repr__ (self ):
425
+ return repr (self .scriptWitness )
426
+
427
+ def is_null (self ):
428
+ return self .scriptWitness .is_null ()
429
+
430
+
431
+ class CTxWitness (object ):
432
+ def __init__ (self ):
433
+ self .vtxinwit = []
434
+
435
+ def deserialize (self , f ):
436
+ for i in xrange (len (self .vtxinwit )):
437
+ self .vtxinwit [i ].deserialize (f )
438
+
439
+ def serialize (self ):
440
+ r = ""
441
+ # This is different than the usual vector serialization --
442
+ # we omit the length of the vector, which is required to be
443
+ # the same length as the transaction's vin vector.
444
+ for x in self .vtxinwit :
445
+ r += x .serialize ()
446
+ return r
447
+
448
+ def __repr__ (self ):
449
+ return "CTxWitness(%s)" % \
450
+ (';' .join ([repr (x ) for x in self .vtxinwit ]))
451
+
452
+ def is_null (self ):
453
+ for x in self .vtxinwit :
454
+ if not x .is_null ():
455
+ return False
456
+ return True
457
+
458
+
384
459
class CTransaction (object ):
385
460
def __init__ (self , tx = None ):
386
461
if tx is None :
387
462
self .nVersion = 1
388
463
self .vin = []
389
464
self .vout = []
465
+ self .wit = CTxWitness ()
390
466
self .nLockTime = 0
391
467
self .sha256 = None
392
468
self .hash = None
@@ -395,33 +471,82 @@ def __init__(self, tx=None):
395
471
self .vin = copy .deepcopy (tx .vin )
396
472
self .vout = copy .deepcopy (tx .vout )
397
473
self .nLockTime = tx .nLockTime
398
- self .sha256 = None
399
- self .hash = None
474
+ self .sha256 = tx .sha256
475
+ self .hash = tx .hash
476
+ self .wit = copy .deepcopy (tx .wit )
400
477
401
478
def deserialize (self , f ):
402
479
self .nVersion = struct .unpack ("<i" , f .read (4 ))[0 ]
403
480
self .vin = deser_vector (f , CTxIn )
404
- self .vout = deser_vector (f , CTxOut )
481
+ flags = 0
482
+ if len (self .vin ) == 0 :
483
+ flags = struct .unpack ("<B" , f .read (1 ))[0 ]
484
+ # Not sure why flags can't be zero, but this
485
+ # matches the implementation in bitcoind
486
+ if (flags != 0 ):
487
+ self .vin = deser_vector (f , CTxIn )
488
+ self .vout = deser_vector (f , CTxOut )
489
+ else :
490
+ self .vout = deser_vector (f , CTxOut )
491
+ if flags != 0 :
492
+ self .wit .vtxinwit = [CTxinWitness ()]* len (self .vin )
493
+ self .wit .deserialize (f )
405
494
self .nLockTime = struct .unpack ("<I" , f .read (4 ))[0 ]
406
495
self .sha256 = None
407
496
self .hash = None
408
497
409
- def serialize (self ):
498
+ def serialize_without_witness (self ):
499
+ r = ""
500
+ r += struct .pack ("<i" , self .nVersion )
501
+ r += ser_vector (self .vin )
502
+ r += ser_vector (self .vout )
503
+ r += struct .pack ("<I" , self .nLockTime )
504
+ return r
505
+
506
+ # Only serialize with witness when explicitly called for
507
+ def serialize_with_witness (self ):
508
+ flags = 0
509
+ if not self .wit .is_null ():
510
+ flags |= 1
410
511
r = ""
411
512
r += struct .pack ("<i" , self .nVersion )
513
+ if flags :
514
+ dummy = []
515
+ r += ser_vector (dummy )
516
+ r += struct .pack ("<B" , flags )
412
517
r += ser_vector (self .vin )
413
518
r += ser_vector (self .vout )
519
+ if flags & 1 :
520
+ if (len (self .wit .vtxinwit ) != len (self .vin )):
521
+ # vtxinwit must have the same length as vin
522
+ self .wit .vtxinwit = self .wit .vtxinwit [:len (self .vin )]
523
+ for i in xrange (len (self .wit .vtxinwit ), len (self .vin )):
524
+ self .wit .vtxinwit .append (CTxinWitness ())
525
+ r += self .wit .serialize ()
414
526
r += struct .pack ("<I" , self .nLockTime )
415
527
return r
416
528
529
+ # Regular serialization is without witness -- must explicitly
530
+ # call serialize_with_witness to include witness data.
531
+ def serialize (self ):
532
+ return self .serialize_without_witness ()
533
+
534
+ # Recalculate the txid (transaction hash without witness)
417
535
def rehash (self ):
418
536
self .sha256 = None
419
537
self .calc_sha256 ()
420
538
421
- def calc_sha256 (self ):
539
+ # We will only cache the serialization without witness in
540
+ # self.sha256 and self.hash -- those are expected to be the txid.
541
+ def calc_sha256 (self , with_witness = False ):
542
+ if with_witness :
543
+ # Don't cache the result, just return it
544
+ return uint256_from_str (hash256 (self .serialize_with_witness ()))
545
+
422
546
if self .sha256 is None :
423
- self .sha256 = uint256_from_str (hash256 (self .serialize ()))
547
+ self .sha256 = uint256_from_str (hash256 (self .serialize_without_witness ()))
424
548
self .hash = hash256 (self .serialize ())[::- 1 ].encode ('hex_codec' )
549
+ return self .sha256
425
550
426
551
def is_valid (self ):
427
552
self .calc_sha256 ()
@@ -512,17 +637,17 @@ def deserialize(self, f):
512
637
super (CBlock , self ).deserialize (f )
513
638
self .vtx = deser_vector (f , CTransaction )
514
639
515
- def serialize (self ):
640
+ def serialize (self , with_witness = False ):
516
641
r = ""
517
642
r += super (CBlock , self ).serialize ()
518
- r += ser_vector (self .vtx )
643
+ if with_witness :
644
+ r += ser_vector (self .vtx , "serialize_with_witness" )
645
+ else :
646
+ r += ser_vector (self .vtx )
519
647
return r
520
648
521
- def calc_merkle_root (self ):
522
- hashes = []
523
- for tx in self .vtx :
524
- tx .calc_sha256 ()
525
- hashes .append (ser_uint256 (tx .sha256 ))
649
+ # Calculate the merkle root given a vector of transaction hashes
650
+ def get_merkle_root (self , hashes ):
526
651
while len (hashes ) > 1 :
527
652
newhashes = []
528
653
for i in xrange (0 , len (hashes ), 2 ):
@@ -531,6 +656,24 @@ def calc_merkle_root(self):
531
656
hashes = newhashes
532
657
return uint256_from_str (hashes [0 ])
533
658
659
+ def calc_merkle_root (self ):
660
+ hashes = []
661
+ for tx in self .vtx :
662
+ tx .calc_sha256 ()
663
+ hashes .append (ser_uint256 (tx .sha256 ))
664
+ return self .get_merkle_root (hashes )
665
+
666
+ def calc_witness_merkle_root (self ):
667
+ # For witness root purposes, the hash of the
668
+ # coinbase, with witness, is defined to be 0...0
669
+ hashes = [ser_uint256 (0 )]
670
+
671
+ for tx in self .vtx [1 :]:
672
+ # Calculate the hashes with witness data
673
+ hashes .append (ser_uint256 (tx .calc_sha256 (True )))
674
+
675
+ return self .get_merkle_root (hashes )
676
+
534
677
def is_valid (self ):
535
678
self .calc_sha256 ()
536
679
target = uint256_from_compact (self .nBits )
@@ -806,11 +949,16 @@ def deserialize(self, f):
806
949
self .tx .deserialize (f )
807
950
808
951
def serialize (self ):
809
- return self .tx .serialize ()
952
+ return self .tx .serialize_without_witness ()
810
953
811
954
def __repr__ (self ):
812
955
return "msg_tx(tx=%s)" % (repr (self .tx ))
813
956
957
+ class msg_witness_tx (msg_tx ):
958
+
959
+ def serialize (self ):
960
+ return self .tx .serialize_with_witness ()
961
+
814
962
815
963
class msg_block (object ):
816
964
command = "block"
@@ -830,6 +978,12 @@ def serialize(self):
830
978
def __repr__ (self ):
831
979
return "msg_block(block=%s)" % (repr (self .block ))
832
980
981
+ class msg_witness_block (msg_block ):
982
+
983
+ def serialize (self ):
984
+ r = self .block .serialize (with_witness = True )
985
+ return r
986
+
833
987
834
988
class msg_getaddr (object ):
835
989
command = "getaddr"
@@ -929,6 +1083,7 @@ def serialize(self):
929
1083
def __repr__ (self ):
930
1084
return "msg_sendheaders()"
931
1085
1086
+
932
1087
# getheaders message has
933
1088
# number of entries
934
1089
# vector of hashes
@@ -1016,6 +1171,8 @@ def __init__(self):
1016
1171
# tests; it causes message delivery to sleep for the specified time
1017
1172
# before acquiring the global lock and delivering the next message.
1018
1173
self .deliver_sleep_time = None
1174
+ # Remember the services our peer has advertised
1175
+ self .peer_services = None
1019
1176
1020
1177
def set_deliver_sleep_time (self , value ):
1021
1178
with mininode_lock :
@@ -1053,6 +1210,7 @@ def on_version(self, conn, message):
1053
1210
conn .ver_send = min (MY_VERSION , message .nVersion )
1054
1211
if message .nVersion < 209 :
1055
1212
conn .ver_recv = conn .ver_send
1213
+ conn .nServices = message .nServices
1056
1214
1057
1215
def on_verack (self , conn , message ):
1058
1216
conn .ver_recv = conn .ver_send
@@ -1082,6 +1240,7 @@ def on_reject(self, conn, message): pass
1082
1240
def on_close (self , conn ): pass
1083
1241
def on_mempool (self , conn ): pass
1084
1242
def on_pong (self , conn , message ): pass
1243
+ def on_sendheaders (self , conn , message ): pass
1085
1244
1086
1245
1087
1246
# The actual NodeConn class
@@ -1103,15 +1262,17 @@ class NodeConn(asyncore.dispatcher):
1103
1262
"headers" : msg_headers ,
1104
1263
"getheaders" : msg_getheaders ,
1105
1264
"reject" : msg_reject ,
1106
- "mempool" : msg_mempool
1265
+ "mempool" : msg_mempool ,
1266
+ "sendheaders" : msg_sendheaders ,
1107
1267
}
1108
1268
MAGIC_BYTES = {
1109
1269
"mainnet" : "\xf9 \xbe \xb4 \xd9 " , # mainnet
1110
1270
"testnet3" : "\x0b \x11 \x09 \x07 " , # testnet3
1111
- "regtest" : "\xfa \xbf \xb5 \xda " # regtest
1271
+ "regtest" : "\xfa \xbf \xb5 \xda " , # regtest
1272
+ "segnet" : "\x2e \x96 \xea \xca " # segnet
1112
1273
}
1113
1274
1114
- def __init__ (self , dstaddr , dstport , rpc , callback , net = "regtest" , services = 1 ):
1275
+ def __init__ (self , dstaddr , dstport , rpc , callback , net = "regtest" , services = NODE_NETWORK ):
1115
1276
asyncore .dispatcher .__init__ (self , map = mininode_socket_map )
1116
1277
self .log = logging .getLogger ("NodeConn(%s:%d)" % (dstaddr , dstport ))
1117
1278
self .dstaddr = dstaddr
@@ -1126,6 +1287,7 @@ def __init__(self, dstaddr, dstport, rpc, callback, net="regtest", services=1):
1126
1287
self .network = net
1127
1288
self .cb = callback
1128
1289
self .disconnect = False
1290
+ self .nServices = 0
1129
1291
1130
1292
# stuff version msg into sendbuf
1131
1293
vt = msg_version ()
0 commit comments