def gen_blocks(n): global blocks, num_blocks block = Block(BlockHeader(timestamp=int(time.time()))) blocks[0] = block for i in range(n): b = Block( BlockHeader(timestamp=int(time.time()), prevhash=blocks[i].hash, number=blocks[i].header.number + 1)) blocks[i + 1] = b num_blocks += 1
def mk_basic_state(alloc, header=None, env=None, executing_on_head=False): state = State(root = "6c08c2bdb7c09eb5a2524e9ed8f3dac707c7b0f6ca2116a173989a5370f77340".decode('hex'),env=environment, executing_on_head=executing_on_head) print(state.get_balance("3282791d6fd713f1e94f4bfd565eaa78b3a0599d")) if not header: header = { "number": 0, "gas_limit": environment.config['BLOCK_GAS_LIMIT'], "gas_used": 0, "timestamp": 1467446877, "difficulty": 1 } h = BlockHeader() state.prev_headers = [h] for addr, data in alloc.items(): addr = normalize_address(addr) assert len(addr) == 20 if 'balance' in data: state.set_balance(addr, parse_as_int(data['balance'])) if 'nonce' in data: state.set_nonce(addr, parse_as_int(data['nonce'])) state.block_number = header["number"] state.timestamp = header["timestamp"] state.commit() environment.db.commit() return state
def get_mining_template(self) -> Block: hdr = BlockHeader(timestamp=get_current_timestamp(), prev_hash=self.get_top_block().hash(), target=int256_to_bytes(FIXED_TARGET), nonce=0x00000000, tx_hash=self.get_queued_tx_hash()) block = Block(header=hdr, txs=self.tx_queue) return block
def response(message): if message is None: print None else: bh, b = ast.literal_eval(message) bh = BlockHeader.deserialize(bh) while not pow(bh.hash(), BOUND): b.nonce +=1 yield resp.put(str((bh.serialize(), b ) ))
def block_from_genesis_declaration(genesis_data, env): h = BlockHeader(timestamp=parse_as_int(genesis_data["timestamp"]), coinbase=parse_as_bin(genesis_data["coinbase"]), prevhash=parse_as_bin(genesis_data["parentHash"]), random_number=parse_as_bin(genesis_data["random_number"]), group_sig=genesis_data["group_sig"], group_pubkey=genesis_data["group_key"], count=parse_as_int(genesis_data["count"])) return Block(h, [])
def parse(cls, stream): # number of headers is in a varint num_headers = read_varint(stream) # initialize the blocks array blocks = [] # loop through number of headers times for _ in range(num_headers): # add a block to the blocks array by parsing the stream blocks.append(BlockHeader.parse(stream)) # read the next varint (num_txs) num_txs = read_varint(stream) # num_txs should be 0 or raise a RuntimeError if num_txs != 0: raise RuntimeError('number of txs not 0') # return a class instance return cls(blocks)
def create_block(self, coinbase, random_no, group_key, group_sig, count): self.chain.process_time_queue() prevhash = self.chain.head_hash prevnumber = self.chain.state.block_number coinbase = normalize_address(coinbase) assert isinstance(random_no, (str, unicode)) if (prevnumber + 1) % DKG_RENEWAL_INTERVAL == 0: if ((group_key is None) or (group_key == '')): raise DkgBlockRequiresGroupKey() else: group_key = "0x00" block = Block( BlockHeader(timestamp=int(time.time()), prevhash=prevhash, number=prevnumber + 1, coinbase=coinbase, random_number=parse_as_bin(random_no), group_pubkey=group_key, group_sig=group_sig, count=count)) snapshot = self.chain.state.to_snapshot() s = state.State().from_snapshot(snapshot, Env(_EphemDB())) databaseLog.info("Creating block with block number %s", str(prevnumber + 1)) for tx in self.transactions: if sys.getsizeof(block) < 1048576: try: dictionary = {} if (prevnumber + 1) % 2 == 0 and int( tx.afi ) == 1: # the next block has to be an IPv4 one apply_transaction(s, tx, dictionary) block.transactions.append(tx) elif (prevnumber + 1) % 2 != 0 and int( tx.afi ) == 2: # the next block has to be an IPv6 one apply_transaction(s, tx, dictionary) block.transactions.append(tx) except Exception as e: databaseLog.info(e.message) else: databaseLog.info("Block number %s filled to max. size", str(prevnumber + 1)) self._create_tries(block) return block
def verify_single_block_multi_transaction_blockchain(tx_pool): blockchain = Blockchain() key_store = KeyStore() block_number = 0 previous_block_hash = blockchain.current_block.block_hash if not blockchain.is_empty( ) else None header = BlockHeader(block_number, previous_block_hash, key_store, config.MINING_DIFFICULTY) txs = [tx_pool.get() for i in xrange(config.BLOCKCHAIN_LENGTH)] block = MultiTransactionBlock(header, txs) if previous_block_hash: blockchain.current_block.header.next_block = block blockchain.accept_block(block) print block logger.info(block) blockchain.verify_chain()
def mk_basic_state(alloc, header=None, env=None, executing_on_head=False): env = env or Env() state = State(env=env, executing_on_head=executing_on_head) if not header: header = {"number": 0, "timestamp": 1467446877} h = BlockHeader(timestamp=parse_as_int(header['timestamp']), number=parse_as_int(header['number'])) state.prev_headers = [h] for addr, data in alloc.items(): addr = normalize_address(addr) assert len(addr) == 20 if 'balance' in data: state.set_balance(addr, parse_as_int(data['balance'])) if 'nonce' in data: state.set_nonce(addr, parse_as_int(data['nonce'])) state.block_number = header["number"] state.timestamp = header["timestamp"] state.commit() return state
from io import BytesIO from network import PeerConnection, GetHeadersMessage, HeadersMessage, GetDataMessage, BlockMessage from block import RAW_GENESIS_BLOCK, BlockHeader, Block GENESIS_HEADER = BlockHeader.parse(BytesIO(RAW_GENESIS_BLOCK)) GENESIS_BLOCK = Block.parse(BytesIO(RAW_GENESIS_BLOCK)) class BitcoinNode: def __init__(self): self.headers = [GENESIS_HEADER] self.blocks = [GENESIS_BLOCK] self.peer = None def connect(self, host, port): self.peer = PeerConnection(host, port) self.peer.handshake() def receive_header(self, header): # append block headers received to headers array self.headers.append(header) def request_headers(self): # get "getheaders" message start_block = self.headers[-1].hash() getheaders = GetHeadersMessage(start_block=start_block) self.peer.send(getheaders) # wait for the "headers" response headers_msg = self.peer.wait_for(HeadersMessage)
import transactions import trie import rlp from db import LevelDB, EphemDB from random import randint env = Env(LevelDB('./chain')) chain = Chain(genesis=mk_genesis_data(env), env=env) prevhash = chain.head_hash prevnumber = chain.state.block_number for i in range(0, 20): print("iteration " + str(i)) block = Block( BlockHeader(timestamp=int(time.time()), prevhash=prevhash, number=prevnumber + 1)) t = trie.Trie(EphemDB()) for j in range(0, 3): transaction = transactions.Transaction(i * 3 + j, '', "192.172.9.1/28", 0, 'data', 1, 1, 1) block.transactions.append(transaction) t.update(rlp.encode(j), rlp.encode(transaction)) block.header.tx_root = t.root_hash chain.add_block(block) prevhash = block.hash prevnumber = prevnumber + 1 chain.process_time_queue() time.sleep(2) # para que timestamp (padre) != timestamp (hijo) block = chain.get_block_by_number(2)