Class: Reth::ChainService
- Inherits:
-
DEVp2p::WiredService
- Object
- DEVp2p::WiredService
- Reth::ChainService
- Defined in:
- lib/reth/chain_service.rb
Constant Summary collapse
- BLOCK_QUEUE_SIZE =
512
- TRANSACTION_QUEUE_SIZE =
512
- MAX_NEWBLOCK_PROCESSING_TIME_STATS =
1000
Instance Attribute Summary collapse
-
#block_queue ⇒ Object
readonly
Returns the value of attribute block_queue.
-
#chain ⇒ Object
readonly
Returns the value of attribute chain.
-
#synchronizer ⇒ Object
readonly
Returns the value of attribute synchronizer.
-
#transaction_queue ⇒ Object
readonly
Returns the value of attribute transaction_queue.
Instance Method Summary collapse
- #add_block(t_block, proto) ⇒ Object
- #add_blocks ⇒ Object
- #add_mined_block(block) ⇒ Object
- #add_transaction(tx, origin = nil, force_broadcast = false) ⇒ Object
- #broadcast_newblock(block, chain_difficulty = nil, origin = nil) ⇒ Object
- #broadcast_transaction(tx, origin = nil) ⇒ Object
-
#initialize(app) ⇒ ChainService
constructor
A new instance of ChainService.
-
#knows_block(blockhash) ⇒ Object
if block is in chain or in queue.
- #mining? ⇒ Boolean
- #on_receive_blockhashes(proto, blockhashes) ⇒ Object
- #on_receive_blocks(proto, transient_blocks) ⇒ Object
- #on_receive_getblockhashes(proto, options) ⇒ Object
- #on_receive_getblockhashesfromnumber(proto, options) ⇒ Object
- #on_receive_getblocks(proto, blockhashes) ⇒ Object
- #on_receive_newblock(proto, options) ⇒ Object
- #on_receive_newblockhashes(proto, newblockhashes) ⇒ Object
- #on_receive_status(proto, options) ⇒ Object
- #on_receive_transactions(proto, transactions) ⇒ Object
- #on_wire_protocol_start(proto) ⇒ Object
- #on_wire_protocol_stop(proto) ⇒ Object
- #start ⇒ Object
- #stop ⇒ Object
- #syncing? ⇒ Boolean
Constructor Details
#initialize(app) ⇒ ChainService
Returns a new instance of ChainService.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/reth/chain_service.rb', line 26 def initialize(app) setup_db(app) super(app) logger.info 'initializing chain' coinbase = app.services.accounts.coinbase env = Env.new @db, config: config[:eth][:block] @chain = Chain.new env, new_head_cb: method(:on_new_head), coinbase: coinbase logger.info 'chain at', number: @chain.head.number if config[:eth][:genesis_hash] raise AssertError, "Genesis hash mismatch. Expected: #{config[:eth][:genesis_hash]}, Got: #{@chain.genesis.full_hash_hex}" unless config[:eth][:genesis_hash] == @chain.genesis.full_hash_hex end @synchronizer = Synchronizer.new(self, nil) @block_queue = SyncQueue.new BLOCK_QUEUE_SIZE @transaction_queue = SyncQueue.new TRANSACTION_QUEUE_SIZE @add_blocks_lock = false @add_transaction_lock = Mutex.new # TODO: should be semaphore @broadcast_filter = DuplicatesFilter.new @on_new_head_cbs = [] @on_new_head_candidate_cbs = [] @newblock_processing_times = [] @processed_gas = 0 @processed_elapsed = 0 @wire_protocol = ETHProtocol end |
Instance Attribute Details
#block_queue ⇒ Object (readonly)
Returns the value of attribute block_queue.
24 25 26 |
# File 'lib/reth/chain_service.rb', line 24 def block_queue @block_queue end |
#chain ⇒ Object (readonly)
Returns the value of attribute chain.
24 25 26 |
# File 'lib/reth/chain_service.rb', line 24 def chain @chain end |
#synchronizer ⇒ Object (readonly)
Returns the value of attribute synchronizer.
24 25 26 |
# File 'lib/reth/chain_service.rb', line 24 def synchronizer @synchronizer end |
#transaction_queue ⇒ Object (readonly)
Returns the value of attribute transaction_queue.
24 25 26 |
# File 'lib/reth/chain_service.rb', line 24 def transaction_queue @transaction_queue end |
Instance Method Details
#add_block(t_block, proto) ⇒ Object
118 119 120 121 122 123 124 |
# File 'lib/reth/chain_service.rb', line 118 def add_block(t_block, proto) @block_queue.enq [t_block, proto] # blocks if full if !@add_blocks_lock @add_blocks_lock = true Thread.new { add_blocks } end end |
#add_blocks ⇒ Object
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
# File 'lib/reth/chain_service.rb', line 126 def add_blocks logger.debug 'add_blocks', qsize: @block_queue.size, add_tx_lock: @add_transaction_lock.locked? raise AssertError unless @add_blocks_lock @add_transaction_lock.lock while !@block_queue.empty? t_block, proto = @block_queue.peek if @chain.include?(t_block.header.full_hash) logger.warn 'known block', block: t_block @block_queue.deq next end if !@chain.include?(t_block.header.prevhash) logger.warn 'missing parent', block: t_block, head: @chain.head @block_queue.deq next end block = nil begin # deserialize t = Time.now block = t_block.to_block @chain.env elapsed = Time.now - t logger.debug 'deserialized', elapsed: elapsed, gas_used: block.gas_used, gpsec: gpsec(block.gas_used, elapsed) rescue InvalidTransaction => e logger.warn 'invalid transaction', block: t_block, error: e errtype = case e when InvalidNonce then 'InvalidNonce' when InsufficientBalance then 'NotEnoughCash' when InsufficientStartGas then 'OutOfGasBase' else 'other_transaction_error' end warn_invalid t_block, errtype @block_queue.deq next rescue ValidationError => e logger.warn 'verification failed', error: e warn_invalid t_block, 'other_block_error' @block_queue.deq next end # all check passed logger.debug 'adding', block: block t = Time.now if @chain.add_block(block, mining?) logger.info 'added', block: block, txs: block.transaction_count, gas_used: block.gas_used, time: (Time.now-t) now = Time.now.to_i if t_block. && t_block. > 0 total = now - t_block. @newblock_processing_times.push total @newblock_processing_times.shift if @newblock_processing_times.size > MAX_NEWBLOCK_AGE avg = @newblock_processing_times.reduce(0.0, &:+) / @newblock_processing_times.size max = @newblock_processing_times.max min = @newblock_processing_times.min logger.info 'processing time', last: total, avg: avg, max: max, min: min end else logger.warn 'could not add', block: block end @block_queue.deq sleep 0.001 end rescue logger.error $! logger.error $!.backtrace[0,10].join("\n") ensure @add_blocks_lock = false @add_transaction_lock.unlock end |
#add_mined_block(block) ⇒ Object
202 203 204 205 206 207 208 209 210 211 212 |
# File 'lib/reth/chain_service.rb', line 202 def add_mined_block(block) logger.debug 'adding mined block', block: block raise ArgumentError, 'block must be Block' unless block.is_a?(Block) raise AssertError, 'invalid pow' unless block.header.check_pow if @chain.add_block(block) logger.debug 'added', block: block raise AssertError, 'block is not head' unless block == @chain.head broadcast_newblock block, block.chain_difficulty end end |
#add_transaction(tx, origin = nil, force_broadcast = false) ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
# File 'lib/reth/chain_service.rb', line 74 def add_transaction(tx, origin=nil, force_broadcast=false) if syncing? if force_broadcast raise AssertError, 'only allowed for local txs' if origin logger.debug 'force broadcasting unvalidated tx' broadcast_transaction tx, origin end return end logger.debug 'add_transaction', locked: !@add_transaction_lock.locked?, tx: tx raise ArgumentError, 'tx must be Transaction' unless tx.instance_of?(Transaction) raise ArgumentError, 'origin must be nil or DEVp2p::Protocol' unless origin.nil? || origin.is_a?(DEVp2p::Protocol) if @broadcast_filter.include?(tx.full_hash) logger.debug 'discarding known tx' return end begin @chain.head_candidate.validate_transaction tx logger.debug 'valid tx, broadcasting' broadcast_transaction tx, origin rescue InvalidTransaction => e logger.debug 'invalid tx', error: e return end if origin # not locally added via jsonrpc if !mining? || syncing? logger.debug 'discarding tx', syncing: syncing?, mining: mining? return end end @add_transaction_lock.lock success = @chain.add_transaction tx @add_transaction_lock.unlock on_new_head_candidate if success success end |
#broadcast_newblock(block, chain_difficulty = nil, origin = nil) ⇒ Object
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
# File 'lib/reth/chain_service.rb', line 222 def broadcast_newblock(block, chain_difficulty=nil, origin=nil) unless chain_difficulty raise AssertError, 'block not in chain' unless @chain.include?(block.full_hash) chain_difficulty = block.chain_difficulty end raise ArgumentError, 'block must be Block or TransientBlock' unless block.is_a?(Block) or block.instance_of?(TransientBlock) if @broadcast_filter.update(block.header.full_hash) logger.debug 'broadcasting newblock', origin: origin exclude_peers = origin ? [origin.peer] : [] app.services.peermanager.broadcast(ETHProtocol, 'newblock', [block, chain_difficulty], {}, nil, exclude_peers) else logger.debug 'already broadcasted block' end end |
#broadcast_transaction(tx, origin = nil) ⇒ Object
239 240 241 242 243 244 245 246 247 248 249 |
# File 'lib/reth/chain_service.rb', line 239 def broadcast_transaction(tx, origin=nil) raise ArgumentError, 'tx must be Transaction' unless tx.instance_of?(Transaction) if @broadcast_filter.update(tx.full_hash) logger.debug 'broadcasting tx', origin: origin exclude_peers = origin ? [origin.peer] : [] app.services.peermanager.broadcast ETHProtocol, 'transactions', [tx], {}, nil, exclude_peers else logger.debug 'already broadcasted tx' end end |
#knows_block(blockhash) ⇒ Object
if block is in chain or in queue
217 218 219 220 |
# File 'lib/reth/chain_service.rb', line 217 def knows_block(blockhash) return true if @chain.include?(blockhash) @block_queue.queue.any? {|(block, proto)| block.header.full_hash == blockhash } end |
#mining? ⇒ Boolean
70 71 72 |
# File 'lib/reth/chain_service.rb', line 70 def mining? app.services.include?('pow') && app.services.pow.active? end |
#on_receive_blockhashes(proto, blockhashes) ⇒ Object
360 361 362 363 364 365 366 367 368 |
# File 'lib/reth/chain_service.rb', line 360 def on_receive_blockhashes(proto, blockhashes) if blockhashes.empty? logger.debug 'recv 0 remote block hashes, signifying genesis block' else logger.debug 'on receive blockhashes', count: blockhashes.size, remote_id: proto, first: Utils.encode_hex(blockhashes.first), last: Utils.encode_hex(blockhashes.last) end @synchronizer.receive_blockhashes proto, blockhashes end |
#on_receive_blocks(proto, transient_blocks) ⇒ Object
388 389 390 391 392 393 394 395 |
# File 'lib/reth/chain_service.rb', line 388 def on_receive_blocks(proto, transient_blocks) blk_number = transient_blocks.empty? ? 0 : transient_blocks.map {|blk| blk.header.number }.max logger.debug 'recv blocks', count: transient_blocks.size, remote_id: proto, highest_number: blk_number unless transient_blocks.empty? @synchronizer.receive_blocks proto, transient_blocks end end |
#on_receive_getblockhashes(proto, options) ⇒ Object
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 |
# File 'lib/reth/chain_service.rb', line 323 def on_receive_getblockhashes(proto, ) child_block_hash = [:child_block_hash] count = [:count] logger.debug 'handle getblockhashes', count: count, block_hash: Utils.encode_hex(child_block_hash) max_hashes = [count, @wire_protocol::MAX_GETBLOCKHASHES_COUNT].min found = [] unless @chain.include?(child_block_hash) logger.debug 'unknown block' proto.send_blockhashes return end last = child_block_hash while found.size < max_hashes begin last = RLP.decode_lazy(@chain.db.get(last))[0][0] # [head][prevhash] rescue KeyError # this can happen if we started a chain download, which did not complete # should not happen if the hash is part of the canonical chain logger.warn 'KeyError in getblockhashes', hash: last break end if last found.push(last) else break end end logger.debug 'sending: found block_hashes', count: found.size proto.send_blockhashes *found end |
#on_receive_getblockhashesfromnumber(proto, options) ⇒ Object
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 |
# File 'lib/reth/chain_service.rb', line 408 def on_receive_getblockhashesfromnumber(proto, ) number = [:number] count = [:count] logger.debug 'recv getblockhashesfromnumber', number: number, count: count, remote_id: proto found = [] count = [count, @wire_protocol::MAX_GETBLOCKHASHES_COUNT].min for i in (number...(number+count)) begin h = @chain.index.get_block_by_number(i) found.push h rescue KeyError logger.debug 'unknown block requested', number: number end end logger.debug 'sending: found block_hashes', count: found.size proto.send_blockhashes *found end |
#on_receive_getblocks(proto, blockhashes) ⇒ Object
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 |
# File 'lib/reth/chain_service.rb', line 370 def on_receive_getblocks(proto, blockhashes) logger.debug 'on receive getblocks', count: blockhashes.size found = [] blockhashes[0, @wire_protocol::MAX_GETBLOCKS_COUNT].each do |bh| begin found.push @chain.db.get(bh) rescue KeyError logger.debug 'unknown block requested', block_hash: Utils.encode_hex(bh) end end unless found.empty? logger.debug 'found', count: found.dize proto.send_blocks *found end end |
#on_receive_newblock(proto, options) ⇒ Object
397 398 399 400 401 402 403 404 405 406 |
# File 'lib/reth/chain_service.rb', line 397 def on_receive_newblock(proto, ) block = [:block] chain_difficulty = [:chain_difficulty] logger.debug 'recv newblock', block: block, remote_id: proto @synchronizer.receive_newblock proto, block, chain_difficulty rescue logger.debug $! logger.debug $!.backtrace[0,10].join("\n") end |
#on_receive_newblockhashes(proto, newblockhashes) ⇒ Object
316 317 318 319 320 321 |
# File 'lib/reth/chain_service.rb', line 316 def on_receive_newblockhashes(proto, newblockhashes) logger.debug 'recv newblockhashes', num: newblockhashes.size, remote_id: proto raise AssertError, 'cannot handle more than 32 block hashes at one time' unless newblockhashes.size <= 32 @synchronizer.receive_newblockhashes(proto, newblockhashes) end |
#on_receive_status(proto, options) ⇒ Object
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
# File 'lib/reth/chain_service.rb', line 269 def on_receive_status(proto, ) eth_version = [:eth_version] network_id = [:network_id] chain_difficulty = [:chain_difficulty] chain_head_hash = [:chain_head_hash] genesis_hash = [:genesis_hash] logger.debug 'status received', proto: proto, eth_version: eth_version raise ETHProtocolError, 'eth version mismatch' unless eth_version == proto.version if network_id != config[:eth].fetch(:network_id, proto.network_id) logger.warn 'invalid network id', remote_network_id: network_id, expected_network_id: config[:eth].fetch(:network_id, proto.network_id) raise ETHProtocolError, 'wrong network id' end # check genesis if genesis_hash != @chain.genesis.full_hash logger.warn 'invalid genesis hash', remote_id: proto, genesis: Utils.encode_hex(genesis_hash) raise ETHProtocolError, 'wrong genesis block' end # request chain @synchronizer.receive_status proto, chain_head_hash, chain_difficulty # send transactions transactions = @chain.get_transactions unless transactions.empty? logger.debug 'sending transactions', remote_id: proto proto.send_transactions *transactions end rescue ETHProtocolError app.services.peermanager.exclude proto.peer rescue logger.error $! logger.error $!.backtrace[0,10].join("\n") end |
#on_receive_transactions(proto, transactions) ⇒ Object
306 307 308 309 310 311 312 313 314 |
# File 'lib/reth/chain_service.rb', line 306 def on_receive_transactions(proto, transactions) logger.debug 'remote transactions received', count: transactions.size, remote_id: proto transactions.each do |tx| add_transaction tx, proto end rescue logger.debug $! logger.debug $!.backtrace[0,10].join("\n") end |
#on_wire_protocol_start(proto) ⇒ Object
251 252 253 254 255 256 257 258 259 260 261 262 |
# File 'lib/reth/chain_service.rb', line 251 def on_wire_protocol_start(proto) logger.debug 'on_wire_protocol_start', proto: proto raise AssertError, 'incompatible protocol' unless proto.instance_of?(@wire_protocol) # register callbacks %i(status newblockhashes transactions getblockhashes blockhashes getblocks blocks newblock getblockhashesfromnumber).each do |cmd| proto.send(:"receive_#{cmd}_callbacks").push method(:"on_receive_#{cmd}") end head = @chain.head proto.send_status head.chain_difficulty, head.full_hash, @chain.genesis.full_hash end |
#on_wire_protocol_stop(proto) ⇒ Object
264 265 266 267 |
# File 'lib/reth/chain_service.rb', line 264 def on_wire_protocol_stop(proto) raise AssertError, 'incompatible protocol' unless proto.instance_of?(@wire_protocol) logger.debug 'on_wire_protocol_stop', proto: proto end |
#start ⇒ Object
58 59 60 |
# File 'lib/reth/chain_service.rb', line 58 def start # do nothing end |
#stop ⇒ Object
62 63 64 |
# File 'lib/reth/chain_service.rb', line 62 def stop # do nothing end |
#syncing? ⇒ Boolean
66 67 68 |
# File 'lib/reth/chain_service.rb', line 66 def syncing? @synchronizer.syncing? end |