Created
November 22, 2022 09:31
-
-
Save mattbajorek/f924525c9862ad7b3a3e72cf5b7ce7ee to your computer and use it in GitHub Desktop.
Chaincode Labs Bitcoin Protocol Development Seminar Exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Chaincode Exercise | |
Try getting node 1 to mine another block, | |
send it to node 2, and check that node 2 received it. | |
""" | |
from collections import defaultdict | |
from test_framework.blocktools import ( | |
create_block, | |
create_coinbase, | |
) | |
from test_framework.p2p import ( | |
P2PInterface, | |
p2p_lock, | |
) | |
from test_framework.test_framework import BitcoinTestFramework | |
from test_framework.util import ( | |
assert_equal, | |
) | |
class BaseNode(P2PInterface): | |
def __init__(self): | |
super().__init__() | |
self.block_receive_map = defaultdict(int) | |
def on_block(self, message): | |
message.block.calc_sha256() | |
self.block_receive_map[message.block.sha256] += 1 | |
class ChaincodeLabsExercise(BitcoinTestFramework): | |
def set_test_params(self): | |
self.num_nodes = 3 | |
def run_test(self): | |
# Setup send and receive | |
node2 = self.nodes[2].add_p2p_connection(BaseNode()) | |
# Generate block from node 1 and send it on the network | |
new_block_hash = int(self.generate(self.nodes[1], nblocks=1)[0], 16) | |
""" Alternative more explicit way | |
chain_tips = self.nodes[1].getchaintips()[0] | |
best_block_hash = int(chain_tips['hash'], 16) | |
best_block_height = chain_tips['height'] | |
new_block_height = best_block_height+1 | |
new_block = create_block(best_block_hash, create_coinbase(new_block_height)) | |
new_block.solve() | |
new_block_hash = new_block.sha256 | |
self.nodes[1].submitblock(new_block.serialize().hex()) | |
""" | |
node2.wait_until(lambda: len(node2.block_receive_map) == 1) | |
with p2p_lock: | |
assert_equal(node2.block_receive_map[new_block_hash], 1) | |
if __name__ == '__main__': | |
ChaincodeLabsExercise().main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment