def genesis(*args): if len(args) == 2 and ':' not in args[0]: return blocks.genesis({args[0]: int(args[1])}).hex_serialize() else: o = {} for a in args: o[a[:a.find(':')]] = int(a[a.find(':') + 1:]) return blocks.genesis(o).hex_serialize()
def mkgenesis(*args): if len(args) == 2 and ':' not in args[0]: return blocks.genesis({ args[0]: int(args[1])}).serialize().encode('hex') else: o = {} for a in args: o[a[:a.find(':')]] = int(a[a.find(':') + 1:]) return blocks.genesis(o).serialize().encode('hex')
def _initialize_blockchain(self, genesis=None): logger.info('Initializing new chain @ %s', utils.get_db_path()) if not genesis: genesis = blocks.genesis() self.index.add_block(genesis) self._store_block(genesis) self._update_head(genesis)
def __init__(self): super(ChainManager, self).__init__() # initialized after configure self.miner = None self.blockchain = None self.synchronizer = Synchronizer(self) self.genesis = blocks.CachedBlock.create_cached(blocks.genesis())
def _recv_Status(self, data): # [0x10: P, protocolVersion: P, networkID: P, totalDifficulty: P, latestHash: B_32, genesisHash: B_32] # check compatibility try: ethereum_protocol_version, network_id = idec(data[0]), idec( data[1]) total_difficulty, head_hash, genesis_hash = idec( data[2]), data[3], data[4] except IndexError: return self.send_Disconnect( reason='Incompatible network protocols') logger.debug( '%r, received Status ETHPROTOCOL:%r TD:%d HEAD:%r GENESIS:%r', self, ethereum_protocol_version, total_difficulty, head_hash.encode('hex'), genesis_hash.encode('hex')) if ethereum_protocol_version != packeter.ETHEREUM_PROTOCOL_VERSION: return self.send_Disconnect( reason='Incompatible network protocols') if network_id != packeter.NETWORK_ID: return self.send_Disconnect(reason='Wrong genesis block') if genesis_hash != blocks.genesis().hash: return self.send_Disconnect(reason='Wrong genesis block') self.status_received = True self.status_head_hash = head_hash self.status_total_difficulty = total_difficulty signals.peer_status_received.send(sender=Peer, peer=self)
def peer_handshake(sender, peer, **kwargs): # reply with status if not yet sent if peer.has_ethereum_capabilities() and not peer.status_sent: logger.debug("%r handshake, sending status", peer) peer.send_Status(chain_manager.head.hash, chain_manager.head.chain_difficulty(), blocks.genesis().hash)
def _recv_Status(self, data): # [0x10: P, protocolVersion: P, networkID: P, totalDifficulty: P, latestHash: B_32, genesisHash: B_32] # check compatibility try: ethereum_protocol_version, network_id = idec(data[0]), idec(data[1]) total_difficulty, head_hash, genesis_hash = idec(data[2]), data[3], data[4] except IndexError: return self.send_Disconnect(reason='Incompatible network protocols') logger.debug('%r, received Status ETHPROTOCOL:%r TD:%d HEAD:%r GENESIS:%r', self, ethereum_protocol_version, total_difficulty, head_hash.encode('hex'), genesis_hash.encode('hex')) if ethereum_protocol_version != packeter.ETHEREUM_PROTOCOL_VERSION: return self.send_Disconnect(reason='Incompatible network protocols') if network_id != packeter.NETWORK_ID: return self.send_Disconnect(reason='Wrong genesis block') if genesis_hash != blocks.genesis().hash: return self.send_Disconnect(reason='Wrong genesis block') self.status_received = True self.status_head_hash = head_hash self.status_total_difficulty = total_difficulty signals.peer_status_received.send(sender=Peer, peer=self)
def receive_chain(self, transient_blocks, peer=None): with self.lock: old_head = self.head # assuming to receive chain order w/ oldest block first transient_blocks.sort(key=attrgetter('number')) assert transient_blocks[0].number <= transient_blocks[-1].number # notify syncer self.synchronizer.received_blocks(peer, transient_blocks) for t_block in transient_blocks: # oldest to newest logger.debug('Deserializing %r', t_block) #logger.debug(t_block.rlpdata.encode('hex')) try: block = blocks.Block.deserialize(t_block.rlpdata) except processblock.InvalidTransaction as e: # FIXME there might be another exception in # blocks.deserializeChild when replaying transactions # if this fails, we need to rewind state logger.debug('%r w/ invalid Transaction %r', t_block, e) # stop current syncing of this chain and skip the child blocks self.synchronizer.stop_synchronization(peer) return except blocks.UnknownParentException: if t_block.prevhash == blocks.GENESIS_PREVHASH: logger.debug('Rec Incompatible Genesis %r', t_block) if peer: peer.send_Disconnect(reason='Wrong genesis block') else: # should be a single newly mined block assert t_block.prevhash not in self assert t_block.prevhash != blocks.genesis().hash logger.debug('%s with unknown parent %s, peer:%r', t_block, t_block.prevhash.encode('hex'), peer) if len(transient_blocks) != 1: # strange situation here. # we receive more than 1 block, so it's not a single newly mined one # sync/network/... failed to add the needed parent at some point # well, this happens whenever we can't validate a block! # we should disconnect! logger.warn('%s received, but unknown parent.', len(transient_blocks)) if peer: # request chain for newest known hash self.synchronizer.synchronize_unknown_block( peer, transient_blocks[-1].hash) break if block.hash in self: logger.debug('Known %r', block) else: assert block.has_parent() forward = len( transient_blocks ) == 1 # assume single block is newly mined block success = self.add_block(block, forward=forward) if success: logger.debug('Added %r', block)
def _initialize_blockchain(self, genesis=None): log.info('Initializing new chain') if not genesis: genesis = blocks.genesis(self.blockchain) log.info('new genesis', genesis_hash=genesis) self.index.add_block(genesis) self._store_block(genesis) assert genesis == blocks.get_block(self.blockchain, genesis.hash) self._update_head(genesis) assert genesis.hash in self
def configure(self, config, genesis=None): self.config = config logger.info('Opening chain @ %s', utils.get_db_path()) db = self.blockchain = DB(utils.get_db_path()) self.index = Index(db) if genesis: self._initialize_blockchain(genesis) logger.debug('Chain @ #%d %s', self.head.number, self.head.hex_hash()) self.genesis = blocks.CachedBlock.create_cached(blocks.genesis()) self.new_miner() self.synchronizer = Synchronizer(self)
def receive_chain(self, transient_blocks, peer=None): with self.lock: old_head = self.head # assuming to receive chain order w/ oldest block first transient_blocks.sort(key=attrgetter('number')) assert transient_blocks[0].number <= transient_blocks[-1].number # notify syncer self.synchronizer.received_blocks(peer, transient_blocks) for t_block in transient_blocks: # oldest to newest logger.debug('Deserializing %r', t_block) #logger.debug(t_block.rlpdata.encode('hex')) try: block = blocks.Block.deserialize(t_block.rlpdata) except processblock.InvalidTransaction as e: # FIXME there might be another exception in # blocks.deserializeChild when replaying transactions # if this fails, we need to rewind state logger.debug('%r w/ invalid Transaction %r', t_block, e) # stop current syncing of this chain and skip the child blocks self.synchronizer.stop_synchronization(peer) return except blocks.UnknownParentException: if t_block.prevhash == blocks.GENESIS_PREVHASH: logger.debug('Rec Incompatible Genesis %r', t_block) if peer: peer.send_Disconnect(reason='Wrong genesis block') else: # should be a single newly mined block assert t_block.prevhash not in self assert t_block.prevhash != blocks.genesis().hash logger.debug('%s with unknown parent %s, peer:%r', t_block, t_block.prevhash.encode('hex'), peer) if len(transient_blocks) != 1: # strange situation here. # we receive more than 1 block, so it's not a single newly mined one # sync/network/... failed to add the needed parent at some point # well, this happens whenever we can't validate a block! # we should disconnect! logger.warn('%s received, but unknown parent.', len(transient_blocks)) if peer: # request chain for newest known hash self.synchronizer.synchronize_unknown_block(peer, transient_blocks[-1].hash) break if block.hash in self: logger.debug('Known %r', block) else: assert block.has_parent() forward = len(transient_blocks)==1 # assume single block is newly mined block success = self.add_block(block, forward=forward) if success: logger.debug('Added %r', block)
def configure(self, config, genesis=None, db=None): self.config = config if not db: db_path = utils.db_path(config.get('misc', 'data_dir')) log.info('opening chain', db_path=db_path) db = self.blockchain = DB(db_path) self.blockchain = db self.index = Index(db) if genesis: self._initialize_blockchain(genesis) log.debug('chain @', head_hash=self.head) self.genesis = blocks.genesis(db=db) log.debug('got genesis', genesis_hash=self.genesis) self.new_miner() self.synchronizer = Synchronizer(self)
import serpent import processblock as pb import blocks as b import transactions as t import utils as u import sys k = u.sha3('cow') v = u.privtoaddr(k) k2 = u.sha3('horse') v2 = u.privtoaddr(k2) print "Starting boring transfer test" blk = b.genesis({ v: 10**18 }) assert blk.hex_hash() == b.Block.hex_deserialize(blk.hex_serialize()).hex_hash() # Give tx2 some money gasprice = 10**12 startgas = 1000 # nonce,gasprice,startgas,to,value,data,v,r,s tx = t.Transaction(0,gasprice,startgas,v2,10**16,'').sign(k) assert tx.hex_hash() == t.Transaction.deserialize(tx.serialize()).hex_hash() assert tx.hex_hash() == t.Transaction.hex_deserialize(tx.hex_serialize()).hex_hash() pb.apply_tx(blk,tx) print "New balance of v1: ", blk.get_balance(v)
def _initialize_blockchain(self): logger.info('Initializing new chain @ %s', utils.get_db_path()) genesis = blocks.genesis() self._store_block(genesis) self._update_head(genesis) self.blockchain.commit()
def _initialize_blockchain(self): logger.info('Initializing new chain @ %s', utils.get_db_path()) genesis = blocks.genesis({self_addr: 10**18}) self._store_block(genesis) self._update_head(genesis) self.blockchain.commit()
def __init__(self, chain_manager, peer): self.chain_manager = chain_manager self.peer = peer self.slices = [] # containing the 1st block.hash of every slice self.request(start=blocks.genesis(), end=chain_manager.head)
import serpent import processblock as pb import blocks as b import transactions as t import utils as u import sys k = u.sha3('cow') v = u.privtoaddr(k) k2 = u.sha3('horse') v2 = u.privtoaddr(k2) print("Starting boring transfer test") blk = b.genesis({v: u.denoms.ether * 1}) assert blk.hex_hash() == \ b.Block.deserialize(blk.serialize()).hex_hash() # Give tx2 some money gasprice = 0 startgas = 10000 # nonce,gasprice,startgas,to,value,data,v,r,s tx = t.Transaction(0, gasprice, startgas, v2, u.denoms.finney * 10, '').sign(k) assert blk in set([blk]) assert tx in set([tx]) assert tx.hex_hash() == \
import serpent import processblock as pb import blocks as b import transactions as t import utils as u import sys k = u.sha3('cow') v = u.privtoaddr(k) k2 = u.sha3('horse') v2 = u.privtoaddr(k2) print("Starting boring transfer test") blk = b.genesis({v: u.denoms.ether * 1}) assert blk.hex_hash() == \ b.Block.deserialize(blk.serialize()).hex_hash() # Give tx2 some money gasprice = 0 startgas = 10000 # nonce,gasprice,startgas,to,value,data,v,r,s tx = t.Transaction(0, gasprice, startgas, v2, u.denoms.finney * 10, '').sign(k) assert blk in set([blk]) assert tx in set([tx]) assert tx.hex_hash() == \ t.Transaction.deserialize(tx.serialize()).hex_hash()