repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/rlpx/frame_io.rb
ciri-p2p/lib/ciri/p2p/rlpx/frame_io.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'stringio' require 'forwardable' require 'ciri/core_ext' require 'ciri/rlp/serializable' require_relative 'errors' require_relative 'message' require 'snappy' using Ciri::CoreExt module Ciri module P2P module RLPX class FrameIO extend Forwardable def_delegators :@io, :closed?, :close, :flush # max message size, took 3 byte to store message size, equal to uint24 max size MAX_MESSAGE_SIZE = (1 << 24) - 1 class Error < RLPX::Error end class OverflowError < Error end class InvalidError < Error end attr_accessor :snappy def initialize(io, secrets) @io = io @secrets = secrets @snappy = false # snappy compress mac_aes_version = secrets.mac.size * 8 @mac = OpenSSL::Cipher.new("AES#{mac_aes_version}") @mac.encrypt @mac.key = secrets.mac # init encrypt/decrypt aes_version = secrets.aes.size * 8 @encrypt = OpenSSL::Cipher::AES.new(aes_version, :CTR) @decrypt = OpenSSL::Cipher::AES.new(aes_version, :CTR) zero_iv = "\x00".b * @encrypt.iv_len @encrypt.iv = zero_iv @encrypt.key = secrets.aes @decrypt.iv = zero_iv @decrypt.key = secrets.aes end def send_data(code, data) msg = Message.new(code: code, size: data.size, payload: data) write_msg(msg) end def write_msg(msg) pkg_type = RLP.encode_with_type msg.code, Integer, zero: "\x00" # use snappy compress if enable if snappy if msg.size > MAX_MESSAGE_SIZE raise OverflowError.new("Message size is overflow, msg size: #{msg.size}") end msg.payload = Snappy.deflate(msg.payload) msg.size = msg.payload.size end # write header head_buf = "\x00".b * 32 frame_size = pkg_type.size + msg.size if frame_size > MAX_MESSAGE_SIZE raise OverflowError.new("Message size is overflow, frame size: #{frame_size}") end write_frame_size(head_buf, frame_size) # Can't find related RFC or RLPX Spec, below code is copy from geth # write zero header, but I can't find spec or explanations of 'zero header' head_buf[3..5] = [0xC2, 0x80, 0x80].pack('c*') # encrypt first half head_buf[0...16] = @encrypt.update(head_buf[0...16]) + @encrypt.final # write header mac head_buf[16...32] = update_mac(@secrets.egress_mac, head_buf[0...16]) @io.write head_buf # write encrypt frame write_frame(pkg_type) write_frame(msg.payload) # pad to n*16 bytes if (need_padding = frame_size % 16) > 0 write_frame("\x00".b * (16 - need_padding)) end finish_write_frame # because we use Async::IO::Stream as IO object, we must invoke flush to make sure data is send flush end def read_msg # verify header mac head_buf = read(32) verify_mac = update_mac(@secrets.ingress_mac, head_buf[0...16]) unless Ciri::Utils.secret_compare(verify_mac, head_buf[16...32]) raise InvalidError.new('bad header mac') end # decrypt header head_buf[0...16] = @decrypt.update(head_buf[0...16]) + @decrypt.final # read frame frame_size = read_frame_size head_buf # frame size should padded to n*16 bytes need_padding = frame_size % 16 padded_frame_size = need_padding > 0 ? frame_size + (16 - need_padding) : frame_size frame_buf = read(padded_frame_size) # verify frame mac @secrets.ingress_mac.update(frame_buf) frame_digest = @secrets.ingress_mac.digest verify_mac = update_mac(@secrets.ingress_mac, frame_digest) # clear head_buf 16...32 bytes(header mac), since we will not need it frame_mac = head_buf[16...32] = read(16) unless Ciri::Utils.secret_compare(verify_mac, frame_mac) raise InvalidError.new('bad frame mac') end # decrypt frame frame_content = @decrypt.update(frame_buf) + @decrypt.final frame_content = frame_content[0...frame_size] msg_code = RLP.decode_with_type frame_content[0], Integer msg = Message.new(code: msg_code, size: frame_content.size - 1, payload: frame_content[1..-1]) # snappy decompress if enable if snappy msg.payload = Snappy.inflate(msg.payload) msg.size = msg.payload.size end msg end private def read(length) if (buf = @io.read(length)).nil? @io.close raise EOFError.new('read EOF, connection closed') end buf end def write_frame_size(buf, frame_size) # frame-size: 3-byte integer size of frame, big endian encoded (excludes padding) bytes_of_frame_size = [ frame_size >> 16, frame_size >> 8, frame_size % 256 ] buf[0..2] = bytes_of_frame_size.pack('c*') end def read_frame_size(buf) size_bytes = buf[0..2].each_byte.map(&:ord) (size_bytes[0] << 16) + (size_bytes[1] << 8) + (size_bytes[2]) end def update_mac(mac, seed) # reset mac each time @mac.reset aes_buf = (@mac.update(mac.digest) + @mac.final)[0...@mac.block_size] aes_buf = aes_buf.each_byte.with_index.map {|b, i| b ^ seed[i].ord}.pack('c*') mac.update(aes_buf) # return first 16 byte mac.digest[0...16] end # write encrypt content to @io, and update @secrets.egress_mac def write_frame(string_or_io) if string_or_io.is_a?(IO) while (s = string_or_io.read(4096)) write_frame_string(s) end else write_frame_string(string_or_io) end end def write_frame_string(s) encrypt_content = @encrypt.update(s) + @encrypt.final # update egress_mac @secrets.egress_mac.update encrypt_content @io.write encrypt_content end def finish_write_frame # get frame digest frame_digest = @secrets.egress_mac.digest @io.write update_mac(@secrets.egress_mac, frame_digest) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/rlpx/secrets.rb
ciri-p2p/lib/ciri/p2p/rlpx/secrets.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri module P2P module RLPX # class used to store rplx protocol secrets class Secrets attr_reader :remote_id, :aes, :mac attr_accessor :egress_mac, :ingress_mac def initialize(remote_id: nil, aes:, mac:) @remote_id = remote_id @aes = aes @mac = mac end def ==(other) self.class == other.class && remote_id == other.remote && aes == other.aes && mac == other.mac end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/spec_helper.rb
spec/spec_helper.rb
require "bundler/setup" require "ciri" require_relative 'ciri/helpers/fixture_helpers' require_relative 'ciri/helpers/ethereum_fixture_helpers' RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end config.include FixtureHelpers config.include EthereumFixtureHelpers # set logger require 'ciri/utils/logger' level = %w{1 yes true}.include?(ENV['DEBUG']) ? :debug : :fatal Ciri::Utils::Logger.setup(level: level) end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri_spec.rb
spec/ciri_spec.rb
require 'spec_helper' RSpec.describe Ciri do it "has a version number" do expect(Ciri::VERSION).not_to be nil end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/trie_spec.rb
spec/ciri/trie_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/trie' require 'ciri/rlp' require 'ciri/utils' # copy from https://github.com/ethereum/py-trie/blob/master/tests/test_proof.py RSpec.describe Ciri::Trie do context 'proof' do let(:proof_key_exists) do raw = "0xf90cb8a04775d885f52f833a65f59e300bce864acce42e30c823da57b3bdd0292e9117e8a09bbfc3085ad0d43784e6e453346e64477caca30f5e37d56e76149e9884e7c297f90c73f90211a001b2cf2fa726ef7bec396325edeb9b29e96eb5d50e8ca941c13a2d7b3c322429a0a2ba62e54a88a18b9079a57957d7471316ecb3b68753396f6b56a30d6c43bf55a0d606929e0bd331307cbe569db472df30a551fbecb9498c967281ebef58375f6ca0a888ed40047fa6be2689268954092bacb8778aeb6e160ce16eb43fad14fd46ffa0c909d0aab03a50dceaed5825049abe1f160c66bc04502340fdd630adec4b8b08a078ffb29a6a4fbc1b6a52802449e695f6546f7782f901a856a9aa34a66088f910a0491c51638aed61f8d14401475429c9024fef8dcc5cf9e67d8a7ecc987ed5d6b6a05527a2a020e4b1b6c3cd34435f9c5db350a877ef8cdec2025e76cd12ed2589a5a028a678fabec39aaeaae9bc7623755cdf6f149a33bc8963c1fedf5b7b7c025003a0cf35078f33a91f1951bb118ab097be93b2d57ee2e03607c33708766780204244a0558e2f95260ac5f1d4c3b9a8345264aa80fe38f1cf2047cce3990107ce489a60a0571fb51cecf70b86150df9f994cd7ce6429fa86c8d5d44f7baee3ac05c11b808a0f569ee29c4d234fc8fbac076531d553ecc7ad1380aa22b0acfe2692aee18e8c1a09d6d53581eeef7601d0c4ffc46e4bd0c4532104836f0937cd57ae73deb624ad6a075089208a54e6c933803a3e24fe8feb1c4878cb8719e6289629698d7f232b9a2a0a656b53fccd2c82a4d45e7cff8adf8dbe7f8f644d53c1c9546130e06727ae56d80f90211a0b303a9c131876d51a1493244346a67fed0256bf20d5db00eeb2717ed78c9556aa04c2f0d24372da5df20789cbcc4991ec5d8b5afd1d1aee64cec6fc4e25255650da0be5370f5ef02cd83b20ba036fdcabbed5ff27df7eab38417edcc196d461328f3a0fb244959529f0470011d7d880bed278e259bc9ea4e5fabf9c99daca9b3091e71a0aa62eb14c2f67d25aa2b30b5c10f3c20c56d61b163ebddcac090e24c8be9fe2fa0916c9da284bfc105e2530ec960c05e7d5121c46d6c2decf45224f68ad3c6f16aa0f313dee04cdb96456051dfa113016235e46bdedebfb130afe6315adb5ad437f4a00981b0ea2aecd0c316eeed7edc986590f27e70bb535919cf6cc42901c2d9c931a02dda258ac56a412de5206c4970beb368980f8071edab894b4edda6cb3b98b038a013971266a331fa7df1fe19fa0be6899acbf5edf351984f3da3b0652fd99f7908a066ba25fbbf451d5db305e424a5d247ec63e5230f2c918b4e39618ad14c166ca5a02370158b5504882f4b7c3461fc0e2e5a6d5e7b15756b8de45ffeeeaeb939d18ea043209fb379f3642e8b091c469e4c08077908b9e1ff4d87fdd6fddb8f949e88c2a017581f2f8b82f5e402847dbe9b7a60209427225f9cff06093e8ad76f4bf9f577a036518d62d85c845f52696e181f17897f40d6bb253eaf61278041a7d87d640722a0cc676df705c8e447f4b318c75c2e0ba2355ddc8077dac93bde9b03a04c53ce8c80f90211a0e4d315e0aa0ff9d0a6c2c8425faf22308cea3b91e44504ec9031795ad63ead63a0774dce164a533ae93698127ca0c97e47bbc77538c8939b05927968aada944e4ba089c7a2bde1da06247cde03d952539084e7050c63df79b0fb400635db38a9ef1fa040113ee8b819b7c740926d24932008c515bd97b03bf505713bb5c639d345c40ea0d55f6f6c056f8ef056d2a06ee7437852c992485451686b63104badfd55e9978fa0767fc54b42da5953a1bf20dae29984ef2c92ddc9b89e6ffc762895ff9474bc35a0cb51963221241fdcdbfeef27c8c84feca2aed35088bfbd21ea0eb089e9ddf377a048b81bc326867c216f00332fc74bc92b2c4be179f286a92a480557cdf88bb50aa006c5a183e4b4dcbfc08c3451931457afbbe96682a28da36ddaedc057885541d9a09c7a567f24a8b9f3c1573019acc5aa70033f2ae6d6ee3c0baf72f66a69d987eda0c71dca95ab7ed37ca69fba9ed54b78499559ad78b8daa721ba93bb422c976ee4a0d72213ca3da97c65118f25b25e1ba6ff935a8b28caab12ed8b330fe0a755a9e1a0c2b498b708182369378185fdc3c66b128699a5350c38d3bc9dc8e0d3cd3dc678a0adf0ea26f48f3d35e1b562c17dbaa10a20a4b74a321fd7c91da4c2afb74fb212a0d57e94997e56792c34ed4d4a1ada33e79091d4af77babf89600e99739345df25a082d24f16ca7b1587ef2d8aeab9cdfc828499dc6fc11e67f32d07f8a3edff788580f90211a0c5a5d3387a75fce9e26a97f0815424ee35944143b1850cef10cb605afc5427cba05a55e43f6c6a05f8bca7f1e4db084d06adbfb373faca53b97b55d26e98312b7ca06c0c4cfb5c2867b437c23ccb14f3a96c0123db227cdcfda023a289cf7897b48ea00be7241da21c5ca52974d682eced025dddef7aa343601bda8109b314df35bbcba0e7256232d4c69890d83a42a49e0ac6a101ac94bd72cadd8aa8e8c646ed04e914a0a7acc053cb6f98eb4a29b18b7bda2c98f24dca2ccdc42594e4dc3cf56f7d901da05bd97d46e20a84bca0810fb90b5d0c10259d0d00525a6762562a3262d17ab5d3a0acca67dbc3799182dd75ad85256782a00df4995e3d1468eeac812f6fe6e4ec0ca038ebed807d32d92e0eeb92a7aeeb8d9b3e383c9dc405f2573b46ce210915b2e3a02aedbf4a809f37d1cdef74892e65024d0d85442d9b4c8dac2a3368f39fdee046a064f9dffbfa60973a11c489755fe926d04c583b7212865c2c7d7f3abcf99ad2e9a09480d4b8e4a6d49c53ccc72a786f5d32797ed61861fbaf501987e73ab17296dca01cda72c1181f0bf3e2f0f13c0588a4014a2cc2a1bd604c8b95a6bd7a653426c1a03e30015364463d8ca71d341e6c4f74cd3b2c7cf06ce94f83f3c0726db682aa08a0d0ef12c53c5c008224988db6a76cd677a3003c4415f7d6c9d0fbd39fed2c9ef7a0a62d3eb1806a7ac38a2c35b8f8bfb45e8830823441fabf0e1f9b202f02ad687880f90211a0c117a17b1335273ece8ae83b84568cfe72da5a53c776d718fbe3bfff92874044a006b963ad8d32c05755af2277e53e1afd02f1dd9124682f0229c6d3bc17c432e8a0c4a2b32a6ba8c8123486a09badfab924353fc60c5d984b62d133db3a85ede15ba025a43e614d08be741bc8b5f2632e396f210347995f0aef934f415eab4391ce97a0c954c1f6c8bed86886fe7982457667e17a509c74982801f5fcf8bef61dc0158ea0d3f1e654d722bade697043e5e1040e3f6f84cb1a4518d0a3360e43c7443e1220a0e0060cafece36f702a6acd84ef9b82617b2c1c98ba2d10f97f2bb68a2f712ceba08a27eb1ae8699153f33ba85b662db032013face44473d845a0878aec5d9b3f9ea0cf0c4dbd92bb61539dd03a7ffed508ace4b5816761c23e5c899508d643f9e6b7a09b68d3b078f0fa35a67656965f169d78954232a9ce6dc8b9afb9ff0aaec71413a0480382d6bd005a0da0335951a4facd6cea38677b4c1618cadbb7357eff1b5d26a0413f6c31bf04c351739b0863c37cf54436a282f8d3f440aba06f4478c4ff592aa00cd7558830a0d3addddadb01ac9979613aebab384b25afc4f147d32ab7ae012aa0b873ab0ef490dbce0b296cb37ff170c6260e68fbc8d78860cddc972d6cb64c82a078f21585e901d8dcc5bcb7dacd24f0aec901cd485ab8299711ffcc37a598b4b6a0f3b6dde9b1930841daa339fe248d4f0a24204d6e222d27a5244635aecd3ea20c80f90151a0828b9d850b2f83ac6d62078968a586528ef4d95f0009ebb33e5c4011ec4f707f8080a022eed9893cc35fcae9edc2760d2c9e101c07e845bd109a165f3a686bb94f6df28080a0115d69b37436ab4b46c0a9817a26df02ca52518292acf1f97e9494744d39be1aa0d06459bcbee5a893c865bd15f8b6629a2bbe68eb9d851f28eed5b220f2eaa1f280a060a8cd303a49ddd7a1c9570d00a61b0c4dbb38b05a8be287160f9955f7dfc45580a0bc5217781259f172b963f51723cddbd51c30d2da7e996196d56bef940fd024cba02116ae65b5483758d50941b57b988f120b58854b183404cf8017f83156bced9ca00008435eb5cf62b313f095538e7951e8df9b49fea29c91405f169d82772c7586a03626995aaee672abecb358875c02993efaeb503ad5d274e270c7e2e00e95f944a0cf7f999a1c18a69a76e6a2d5b3458a4a18a78cc007dae90b690d090f9b06f85380f851a0078343d158dfdd4ad4f27f332b0a95b289d2229dc553fbfc9e648dd2d2e5994280808080a02d6d3200ef95cdfef89e0bbfaed8b4d2a12afd65aab18add1d0703c72c3ce8e78080808080808080808080f8669d385ad0d43784e6e453346e64477caca30f5e37d56e76149e9884e7c297b846f8440180a055bd1d6151977b62672c21c2754bbeeb3b8278b2e0c38edcd949846ee3628bf1a01e0b2ad970b365a217c40bcf3582cbb4fcc1642d7a5dd7a82ae1e278e010123e" state_root, key, proof = Ciri::RLP.decode(Ciri::Utils.dehex raw) [state_root, key, proof] end let(:proof_key_does_not_exists) do raw = "0xf90c86a04775d885f52f833a65f59e300bce864acce42e30c823da57b3bdd0292e9117e8a041b1a0649752af1b28b3dc29a1556eee781e4a4c3a1f7f53f90fa834de098c4df90c41f90211a001b2cf2fa726ef7bec396325edeb9b29e96eb5d50e8ca941c13a2d7b3c322429a0a2ba62e54a88a18b9079a57957d7471316ecb3b68753396f6b56a30d6c43bf55a0d606929e0bd331307cbe569db472df30a551fbecb9498c967281ebef58375f6ca0a888ed40047fa6be2689268954092bacb8778aeb6e160ce16eb43fad14fd46ffa0c909d0aab03a50dceaed5825049abe1f160c66bc04502340fdd630adec4b8b08a078ffb29a6a4fbc1b6a52802449e695f6546f7782f901a856a9aa34a66088f910a0491c51638aed61f8d14401475429c9024fef8dcc5cf9e67d8a7ecc987ed5d6b6a05527a2a020e4b1b6c3cd34435f9c5db350a877ef8cdec2025e76cd12ed2589a5a028a678fabec39aaeaae9bc7623755cdf6f149a33bc8963c1fedf5b7b7c025003a0cf35078f33a91f1951bb118ab097be93b2d57ee2e03607c33708766780204244a0558e2f95260ac5f1d4c3b9a8345264aa80fe38f1cf2047cce3990107ce489a60a0571fb51cecf70b86150df9f994cd7ce6429fa86c8d5d44f7baee3ac05c11b808a0f569ee29c4d234fc8fbac076531d553ecc7ad1380aa22b0acfe2692aee18e8c1a09d6d53581eeef7601d0c4ffc46e4bd0c4532104836f0937cd57ae73deb624ad6a075089208a54e6c933803a3e24fe8feb1c4878cb8719e6289629698d7f232b9a2a0a656b53fccd2c82a4d45e7cff8adf8dbe7f8f644d53c1c9546130e06727ae56d80f90211a08d0cca0632c15199f41b494ca0134563bb5aa177fdab99c89b755f03ae6537d7a0f68ed566180474f58acf40da551d0fd5f06348e3b7d3ed324bdc84af7857b519a0c66a9553414e145d510331704a955ea7f0680504d7c7f4ab30666bec654cc111a0fff1267ab5a72b29fe951346d947ae0d4632085b2edfca11cbab1a21c5ab4930a0749a388998cdc27175983e64a17833fa83396c0a54fec872221c518b9b632025a02c4a59bef5e72a5dc2e7fa0245365156aa86e4d50a214d2539bc74eef9338923a030e730085ed4096415f24b7ac114a9472fc824525dbbad828db20a248cf1234ea036ec408ba4243e9dfc4f3b6ca332490bff99c546d50dafebf7e9d1f13ede5ceca01b2c3a1ca936144c21f34ba8a9715b00646992142848ae5547fe52fc1f452deaa0dcc4359cb67fa5b06160d5e540b1983c6c65b9e85572b19aabcd1fdcb82c918fa07888809fdbc0385004dee25e1139acb5b3ee40fd5140e859b6987ed6f111ce72a0d2640c90fdcbd8d5510795f00b68a6304de8030ce581f779005755a58f07accea051905ef4f6e53a4c5468c21d6a9189f635d907ea6f4ab291dd0138a509515f99a039731831a89d8f9046af70712bb27e05799c17e025628611f97915e0c4abe764a08eddec740c5cc871f4b7f2564ae2345720b8616d130169f18e7f9cc740715641a02f4c2294571bb364cb2ba764464117ec45d7f617525106558cc9cfd3370aa08c80f90211a064c7ae40306b89af0ab22e8bd99d17d8de663257f1187b2bb930c3a466686f57a0f66469447c4dd0c2a18c3f57a837fb5f41ac3f4633a700ee945cc46359b3c214a048c4c259c878de574cc5f082e8f17229f800fcb1db91cf2c28b7a2a02fa8727ca0fa8ba3955a99f5e15deca181c4cc02ba53ecb6117d69ac8d532893613e4aab49a093dede01d72b40dab4a9a9065bd5215b336554212e06e8acd776e3a901dc12a5a0141d78a79b85fe42e035c9668f9b27f92506b48f2444da96bad4066e76fda968a07038adb71847c4f22f167f4666a6f633333b1566178016df408228b61ca861a8a0eedb9d9667512ba2cf388719a0c28eedaddfdd02d6d9c14cee00c809211c8cbca02f6021090b8668b258b0a8a990d7b84f14fe77f43f26a104c5af2b2557b77060a05c050efa790cb5d5888227c24f23cc931ae40561e743ad182af65bba1f8d75f3a08bf9b905826f36cf71a4b9d1f288b775b3aff9c52191f8960009ecf5dcf53ebda085757b9a2d7bd23439085495d9becd27c90f300d91ac13b18f6d6fdf37424f91a0a89b9445334ac08439d7bcbeda6066345e0e243f4506f4cddaaeda783581f41ca05566cf80361cf2b97d548b7d91bed20e1eb235f74328f3ef9e80a2a349a36a08a069aa7458d656d8f69d568bb056d0b45f440f4f994acfb8e4325823cb77963d35a077b0fab8d72dd616a7e19f92e3965bd61883b7f91737e33601ee52ace4b3d5ba80f90211a0d5120333ddba0566c4103fea22d593159f1683a0fd8470809d6407d20a5b6faaa08c9842ed44368c7ad58dd49a7c7573b66c479854cc0b9c28fa1eedb71e86a241a090be772dfab6474827df23138f0648053c0ddb66d0994dd245318db35d2e0588a04819ce69d8e22fe147d9705b33adc8f98ca76d67d5c1d13c5acf585e3d139d9da02faa1f7f68804fe14a44dcf9f89288d7ecc227b6ab7d28152f4655b9242e5c6fa02077b17adb71d30b33b4711c3c77a54352cd1f0d34dcc0b97712b0cc379f7098a00f8770ca732a5f440e1701a410732f17c015f164fbba9468d3d9bd80bfd595c5a06f49da85add2c6628ff06475b61484fccc1eb08b9025d08662e70799927b786ca09acefe4ef61f7ca9b639ba0ce24909ed487f96fd3afb63dd6eaccf2004ae86dca0a788788b10709d46d5d2afac2bd584b1e3d698d07a8f298044be96b3c5ee7246a04222c9a2876be0e33399c7a04a7972d82e061e3e1aa6947c2bc71210ba1ec477a0b1e0115e7ac5ec7982606bc5557872644469de0779c96826954124d315624ecda08b5a724bef8a1c8a49affa1e9ccc1c710159689d043b14da91ba95cb140ae5d3a03dfcebc58ef32122c33d2ccf2e3a3e4459235cabe4380ed6171f50e879784179a06fb1bdc478dd9a76601295fb7fbd886deb7f9aa0e0daf079c6a95387e1e4da30a0ef70c6e471e521e06cbbc3f1ede659c88a2dccbed6780ec7f16fc5d93196d4d380f90211a0c47c24edafdedc365234022ae14f5815ea05ae3d7082d7c5254c78e9cd424711a035d4789c0492b17da7dd3eb680729af58fcf5747099035e6a2f9396ccad3ecf8a075b6641a829ef8094e712b03da531c1a6869d8853a8b34fce8e4ae12a2e29cd2a061e6dff7cd8ec8b6d7363d48acf14a1fe561e92db23342c728791a468c2c78fda0e27264cb5f088efd1e73b905018248d2dc794a46a73147a5a471946477ad76f7a07ce4ed0a0645d238a90441e1911f621b3982fa1578429d14515569787e1a8980a00df96b31ee4eab45947d6ee6b1af4ac9fea1f028ff61e58e6d343f311a7b7110a0d37037176af45ca1f301709c6069fbc1b94866a25a546ce4951a3a126b38b04ea0f424f5b9bd34b597d3f52813fefd7fd1a6f276a548cbfb19693a9be75eb8074aa088ae3987cdcc932726586d021b644ecf507df4d10f79f0322c8d7c3dbb0e4c51a0b99d186851e4a51354c2d5f6d8b976390b3aed76ed753c457a5d7290e2dacc4aa0f11b01ae6c474c9dac75d8504b4b20e8ce1f571219ef4d09c4d6f7810c93cfe8a0e7e5c4284ae2a4a8e8e413dfc506dd35dd875777966dfac7d23fd224a125a27ea0c2bd2acf7bf33f0a22947da690be38447fd7939522841510b63cd2b60e3bfb3fa0446efb54e47bca7433910d90d127be7a540c6b8d96004a28fe8e75e6f603f0f3a07839d2528bb22b92b7375a8418fb089ff0c718a8f830dadee01e372e4ad2e1cd80f90171a0c7595b3f2c413210b830d79688b5da6ffcdca1f1713ab57c3158b14d97dc0fe4a0ef5806155c01effdd0faa052d999ba7b8617c2cfe1df31ed90ce65625f670c7aa0da515adf030860b1c07bcb2ffcaa35801531b7f4cfe7df5284ef9a5c0ff7c3aea0ff8883cea400c09f66d90ff2192489cac533cab68ae57217854caabfdffa2648a0d5aa000a86789cdd7ac3c398eddde5e7be77f7048c032e615fc9ed693a5f7ea3a0cc398af6da101d760f8582883459d2d88a15a2cdc6fc272b067d3acffdcdff2b80a094bcd7427ccd36f621ca0ce4026061335579e86d3d1337e72a7189ef35b6b4b5a0348310820602896f7b29e34edb3df3291bfc0be4c44e7f844dbcc7ad11ecb132a0d9df2ef0bae2572da609b517aea4a1b7bb83ff946a9e3ea521f7390f89c8ceb380a0cd894bab92a66374c4c0ea4e31415c93ee3e39070b498569fb58bde5c8a83385a09a494c3b8b2647ff7d9254d6cc9576a069e2ccd47006b4287d0f89ffa5ec208880808080f8679e20171808d8a425d236d025548a58bf8b8c954b77afa54db8185181749e4bb846f8440180a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" state_root, key, proof = Ciri::RLP.decode(Ciri::Utils.dehex raw) [state_root, key, proof] end it 'proof key exists' do state_root, key, proof = proof_key_exists expect(Ciri::Trie.proof(state_root, key, proof)).not_to eq ''.b end it 'proof key not exists' do state_root, key, proof = proof_key_does_not_exists expect(Ciri::Trie.proof(state_root, key, proof)).to eq ''.b end it 'proof invalid' do state_root, key, proof = proof_key_exists proof[5][3] = ''.b expect {Ciri::Trie.proof(state_root, key, proof)}.to raise_error(Ciri::Trie::BadProofError) end it 'proof empty' do state_root = Ciri::Utils.keccak('state root'.b) key = Ciri::Utils.keccak('some key'.b) proof = [] expect {Ciri::Trie.proof(state_root, key, proof)}.to raise_error(Ciri::Trie::BadProofError) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/bloom_filter_spec.rb
spec/ciri/bloom_filter_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/bloom_filter' require 'ciri/types/log_entry' require 'ciri/types/uint' require 'ciri/utils' RSpec.describe Ciri::BloomFilter do it 'with log entry' do address = "\x00".b * 20 topics = 5.times.map {rand(100)} log_entry = Ciri::Types::LogEntry.new(address: address, topics: topics, data: ''.b) bloom_filter = Ciri::BloomFilter.from_iterable(log_entry.to_blooms) topics.each do |topic| expect(bloom_filter.include? Ciri::Types::UInt32.new(topic).to_bytes).to be_truthy end end it 'other values' do bloom_filter = Ciri::BloomFilter.new bloom_filter << "harry potter" expect(bloom_filter.include?("harry potter")).to be_truthy expect(bloom_filter.include?("voldemort")).to be_falsey end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/helpers/ethereum_fixture_helpers.rb
spec/ciri/helpers/ethereum_fixture_helpers.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'yaml' require 'json' module EthereumFixtureHelpers def prepare_ethereum_fixtures system('git submodule init') system('git submodule update fixtures') end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/helpers/fixture_helpers.rb
spec/ciri/helpers/fixture_helpers.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'yaml' require 'json' require 'ciri/core_ext' require 'ciri/pow_chain/chain' using Ciri::CoreExt module FixtureHelpers FIXTURE_DIR = "spec/fixtures" def fixture(file) path = FIXTURE_DIR + '/' + file extname = File.extname(path) # guess file if extname.empty? && !File.exist?(path) if File.exist? path + '.json' extname = '.json' elsif File.exist? path + '.yaml' extname = '.yaml' elsif File.exist? path + '.yml' extname = '.yml' end path += extname end f = open(path) if extname == '.yaml' || extname == '.yml' YAML.load(f.read) elsif extname == '.json' JSON.parse(f.read) else f.read end end BLOCK_HEADER_MAPPING = { bloom: :logs_bloom, coinbase: :beneficiary, miner: :beneficiary, sha3_uncles: :ommers_hash, uncle_hash: :ommers_hash, receipt_trie: :receipts_root, transactions_trie: :transactions_root, } def fixture_to_block_header(b, data = nil) data ||= fixture_normalize(b, BLOCK_HEADER_MAPPING) # convert hex to binary %i{extra_data hash logs_bloom beneficiary mix_hash nonce parent_hash receipts_root ommers_hash state_root transactions_root}.each do |k| data[k] = Ciri::Utils.dehex(data[k]) if data.has_key?(k) end %i{difficulty gas_used gas_limit number timestamp}.each do |k| data[k] = Ciri::Utils.dehex_number(data[k]) if data.has_key?(k) && !data[k].is_a?(Integer) end data = data.select {|k, v| Ciri::POWChain::Header.schema.keys.include? k}.to_h Ciri::POWChain::Header.new(**data) end def fixture_to_block(b, data = nil) data ||= fixture_normalize(b, BLOCK_HEADER_MAPPING) header = fixture_to_block_header(b, data) transactions = data[:transactions] uncles = data[:uncles].map {|u| fixture_to_block(u).header} Ciri::POWChain::Block.new(header: header, transactions: transactions, ommers: uncles) end TRANSACTION_MAPPING = {} def fixture_to_transaction(b, data = nil) data ||= fixture_normalize(b, TRANSACTION_MAPPING) %i{data to}.each do |k| data[k] = Ciri::Utils.dehex(data[k]) if data.has_key?(k) end data[:to] = Ciri::Types::Address.new(data[:to]) %i{gas_used gas_limit gas_price nonce r s v value}.each do |k| data[k] = Ciri::Utils.dehex_number(data[k]) if data.has_key?(k) end Ciri::POWChain::Transaction.new(**data) end def fixture_normalize(b, mapping = {}) b.map do |k, v| k = Ciri::Utils.to_underscore(k).to_sym k = mapping[k] if mapping.has_key?(k) [k, v] end.to_h end def load_blocks(file) require 'ciri/pow_chain/chain' fixture(file).map do |b| fixture_to_block(b) end end def parse_account(account_hash) storage = account_hash["storage"].map do |k, v| [k.dehex.big_endian_decode, v.dehex.big_endian_decode] #[k.dehex, v.dehex.pad_zero(32)] end.to_h account = Ciri::Types::Account.new( balance: account_hash["balance"].dehex.big_endian_decode, nonce: account_hash["nonce"].dehex.big_endian_decode) code = account_hash['code'].dehex [account, code, storage] end def parse_header(data) columns = {} columns[:logs_bloom] = data['bloom'].dehex columns[:beneficiary] = data['coinbase'].dehex columns[:difficulty] = data['difficulty'].dehex.big_endian_decode columns[:extra_data] = data['extraData'].dehex columns[:gas_limit] = data['gasLimit'].dehex.big_endian_decode columns[:gas_used] = data['gasUsed'].dehex.big_endian_decode columns[:mix_hash] = data['mixHash'].dehex columns[:nonce] = data['nonce'].dehex columns[:number] = data['number'].dehex.big_endian_decode columns[:parent_hash] = data['parentHash'].dehex columns[:receipts_root] = data['receiptTrie'].dehex columns[:state_root] = data['stateRoot'].dehex columns[:transactions_root] = data['transactionsTrie'].dehex columns[:timestamp] = data['timestamp'].dehex.big_endian_decode columns[:ommers_hash] = data['uncleHash'].dehex header = Ciri::POWChain::Header.new(**columns) unless Ciri::Utils.hex(header.get_hash) == data['hash'] error columns end header end def extract_fork_config(fixture) network = fixture['network'] schema_rules = case network when "Frontier" [ [0, Ciri::Forks::Frontier::Schema.new], ] when "Homestead" [ [0, Ciri::Forks::Homestead::Schema.new(support_dao_fork: false)], ] when "EIP150" [ [0, Ciri::Forks::TangerineWhistle::Schema.new], ] when "EIP158" [ [0, Ciri::Forks::SpuriousDragon::Schema.new], ] when "Byzantium" [ [0, Ciri::Forks::Byzantium::Schema.new], ] when "Constantinople" [ [0, Ciri::Forks::Constantinople::Schema.new], ] when "FrontierToHomesteadAt5" [ [0, Ciri::Forks::Frontier::Schema.new], [5, Ciri::Forks::Homestead::Schema.new(support_dao_fork: false)], ] when "HomesteadToEIP150At5" [ [0, Ciri::Forks::Homestead::Schema.new(support_dao_fork: false)], [5, Ciri::Forks::TangerineWhistle::Schema.new], ] when "HomesteadToDaoAt5" [ [0, Ciri::Forks::Homestead::Schema.new(support_dao_fork: true, dao_fork_block_number: 5)], ] when "EIP158ToByzantiumAt5" [ [0, Ciri::Forks::SpuriousDragon::Schema.new], [5, Ciri::Forks::Byzantium::Schema.new], ] else raise ArgumentError.new("unknown network: #{network}") end Ciri::Forks::Config.new(schema_rules) end def prepare_state(state, fixture) fixture['pre'].each do |address, v| address = Ciri::Types::Address.new address.dehex account, code, storage = parse_account v state.set_balance(address, account.balance) state.set_nonce(address, account.nonce) state.set_account_code(address, code) storage.each do |key, value| # key, value = k.big_endian_decode, v.big_endian_decode state.store(address, key, value) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/fixtures_tests/evm_spec.rb
spec/ciri/fixtures_tests/evm_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/state' require 'ciri/evm' require 'ciri/evm/execution_context' require 'ciri/types/account' require 'ciri/forks/frontier' require 'ciri/utils' require 'ciri/db/backend/memory' SLOW_TOPIC = ["fixtures/VMTests/vmPerformance"] RSpec.describe Ciri::EVM do before(:all) do prepare_ethereum_fixtures end run_test_case = proc do |test_case, prefix: nil, tags:| test_case.each do |name, t| it "#{prefix} #{name}", **tags do db = Ciri::DB::Backend::Memory.new state = Ciri::State.new(db) # pre t['pre'].each do |address, account_hash| address = Ciri::Utils.dehex(address) account, _code, storage = parse_account(account_hash) state.set_balance(address, account.balance) state.set_nonce(address, account.nonce) storage.each do |key, value| state.store(address, key, value) end end # env # exec gas = Ciri::Utils.big_endian_decode Ciri::Utils.dehex(t['exec']['gas']) address = Ciri::Utils.dehex(t['exec']['address']) origin = Ciri::Utils.dehex(t['exec']['origin']) caller = Ciri::Utils.dehex(t['exec']['caller']) gas_price = Ciri::Utils.big_endian_decode Ciri::Utils.dehex(t['exec']['gasPrice']) code = Ciri::Utils.dehex(t['exec']['code']) value = Ciri::Utils.dehex(t['exec']['value']) data = Ciri::Utils.dehex(t['exec']['data']) env = t['env'] && t['env'].map {|k, v| [k, Ciri::Utils.dehex(v)]}.to_h instruction = Ciri::EVM::Instruction.new(address: address, origin: origin, price: gas_price, sender: caller, bytes_code: code, value: value, data: data) block_info = env && Ciri::EVM::BlockInfo.new( coinbase: env['currentCoinbase'], difficulty: env['currentDifficulty'], gas_limit: env['currentGasLimit'], number: env['currentNumber'], timestamp: env['currentTimestamp'], ) fork_schema = Ciri::Forks::Frontier::Schema.new context = Ciri::EVM::ExecutionContext.new(instruction: instruction, gas_limit: gas, block_info: block_info, fork_schema: fork_schema) vm = Ciri::EVM::VM.new(state: state, burn_gas_on_exception: false) # ignore exception vm.with_context(context) do vm.run(ignore_exception: true) end next unless t['post'] # post output = t['out'].yield_self {|out| out && Ciri::Utils.dehex(out)} if output # padding vm output, cause testcases return length is uncertain vm_output = (context.output || '').rjust(output.size, "\x00".b) expect(vm_output).to eq output end remain_gas = t['gas'].yield_self {|remain_gas| remain_gas && Ciri::Utils.big_endian_decode(Ciri::Utils.dehex(remain_gas))} expect(context.remain_gas).to eq remain_gas if remain_gas state = vm.state t['post'].each do |address, account_hash| address = Ciri::Utils.dehex(address) account, code, storage = parse_account(account_hash) vm_account = state.find_account(address) storage.each do |k, v| data = state.fetch(address, k) expect(Ciri::Utils.hex(data)).to eq Ciri::Utils.hex(v) end expect(vm_account.nonce).to eq account.nonce expect(vm_account.balance).to eq account.balance expect(vm_account.code_hash).to eq account.code_hash end end end end Dir.glob("fixtures/VMTests/*").each do |topic| tags = SLOW_TOPIC.include?(topic) ? {slow: true} : {} Dir.glob("#{topic}/*.json").each do |t| run_test_case[JSON.load(open t), prefix: topic, tags: tags] end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/fixtures_tests/trie_spec.rb
spec/ciri/fixtures_tests/trie_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/trie' require 'ciri/utils' RSpec.describe Ciri::Trie do before(:all) do prepare_ethereum_fixtures end run_test_case = proc do |test_case, prefix: nil, tags: {}| test_case.each do |name, t| it "#{prefix} #{name}", **tags do # in input = t['in'].map do |key, value| [ key.start_with?('0x') ? Ciri::Utils.dehex(key) : key, value&.start_with?('0x') ? Ciri::Utils.dehex(value) : value ] end trie = Ciri::Trie.new input.each do |k, v| if v trie[k] = v else trie.delete(k) end end expect(Ciri::Utils.hex trie.root_hash).to eq (t['root']) end end end Dir.glob("fixtures/TrieTests/trietest.json").each do |topic| run_test_case[JSON.load(open topic), prefix: 'fixtures/TrieTests'] end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/fixtures_tests/block_chain_spec.rb
spec/ciri/fixtures_tests/block_chain_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/core_ext' require 'ciri/pow_chain/chain' require 'ciri/evm' require 'ciri/state' require 'ciri/types/account' require 'ciri/forks/frontier' require 'ciri/utils' require 'ciri/db/backend/memory' require 'ciri/key' using Ciri::CoreExt KNOWN_FAILED_CASE = [ "ShanghaiLove_Homestead", "DelegateCallSpam_Homestead" ] SLOW_TOPIC = [ "fixtures/BlockchainTests/bcExploitTest", "fixtures/BlockchainTests/bcWalletTest" ] RSpec.describe Ciri::POWChain::Chain do include Ciri::Utils::Logger before(:all) do prepare_ethereum_fixtures end def self.run_test_case(test_case, prefix: nil, tags: ) test_case.each do |name, t| # TODO support all forks next skip("#{prefix} #{name}") if name.include?("Constantinople") if KNOWN_FAILED_CASE.include?(name) skip "#{name} still fail, need invesgate" break end # register rspec test case it "#{prefix} #{name}", **tags do db = Ciri::DB::Backend::Memory.new state = Ciri::State.new(db) # pre prepare_state(state, t) genesis = if t['genesisRLP'] Ciri::POWChain::Block.rlp_decode(t['genesisRLP'].dehex) elsif t['genesisBlockHeader'] Ciri::POWChain::Block.new(header: parse_header(t['genesisBlockHeader']), transactions: [], ommers: []) end fork_config = extract_fork_config(t) chain = Ciri::POWChain::Chain.new(db, genesis: genesis, network_id: 0, fork_config: fork_config) # run block t['blocks'].each do |b| begin block = Ciri::POWChain::Block.rlp_decode b['rlp'].dehex chain.import_block(block) rescue Ciri::POWChain::Chain::InvalidBlockError, Ciri::RLP::InvalidError, Ciri::EVM::Error, Ciri::Types::Errors::InvalidError => e error e expect(b['blockHeader']).to be_nil expect(b['transactions']).to be_nil expect(b['uncleHeaders']).to be_nil break end # check status block = chain.get_block(block.get_hash) expect(block.header).to eq fixture_to_block_header(b['blockHeader']) if b['blockHeader'] expect(block.transactions).to eq b['transactions'].map {|t| fixture_to_transaction(t)} if b['transactions'] expect(block.ommers).to eq b['uncleHeaders'].map {|h| fixture_to_block_header(h)} if b['uncleHeaders'] end end end end Dir.glob("fixtures/BlockchainTests/**").each do |topic| tags = SLOW_TOPIC.include?(topic) ? {slow: true} : {} Dir.glob("#{topic}/*.json").each do |t| run_test_case(JSON.load(open t), prefix: topic, tags: tags) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/fixtures_tests/transaction_spec.rb
spec/ciri/fixtures_tests/transaction_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/pow_chain/transaction' require 'ciri/utils' require 'ciri/db/backend/memory' require 'ciri/forks' RSpec.describe Ciri::POWChain::Transaction do before(:all) do prepare_ethereum_fixtures end choose_fork_schema = proc do |fork_name| case fork_name when 'Frontier' Ciri::Forks::Frontier::Schema.new when 'Homestead' Ciri::Forks::Homestead::Schema.new(support_dao_fork: false) when 'EIP150' Ciri::Forks::TangerineWhistle::Schema.new when 'EIP158' Ciri::Forks::SpuriousDragon::Schema.new when 'Byzantium' Ciri::Forks::Byzantium::Schema.new when 'Constantinople' Ciri::Forks::Constantinople::Schema.new else raise ArgumentError.new("unknown fork #{fork_name}") end end run_test_case = proc do |test_case, prefix: nil| test_case.each do |name, t| %w{Byzantium Constantinople EIP150 EIP158 Frontier Homestead}.each do |fork_name| it "#{prefix} #{name} #{fork_name}" do expect_result = t[fork_name] fork_schema = choose_fork_schema[fork_name] transaction = begin rlp = Ciri::Utils.dehex(t['rlp']) transaction = fork_schema.transaction_class.rlp_decode rlp # encoded again and check rlp encoding fork_schema.transaction_class.rlp_encode(transaction) == rlp ? transaction : nil rescue Ciri::RLP::InvalidError, Ciri::Types::Errors::InvalidError nil end begin raise Ciri::POWChain::Transaction::InvalidError if transaction.nil? transaction.validate! rescue Ciri::POWChain::Transaction::InvalidError => e e end unless expect_result.empty? expect(Ciri::Utils.hex transaction.get_hash).to eq "0x#{expect_result['hash']}" expect(Ciri::Utils.hex transaction.sender).to eq "0x#{expect_result['sender']}" end end end end end Dir.glob("fixtures/TransactionTests/*").each do |topic| Dir.glob("#{topic}/*.json").each do |t| run_test_case[JSON.load(open t), prefix: topic] end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/fixtures_tests/evm_state_spec.rb
spec/ciri/fixtures_tests/evm_state_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/evm' require 'ciri/state' require 'ciri/types/account' require 'ciri/forks/frontier' require 'ciri/utils' require 'ciri/db/backend/memory' require 'ciri/pow_chain/transaction' require 'ciri/key' SLOW_TOPIC = [ "fixtures/GeneralStateTests/stQuadraticComplexityTest", "fixtures/GeneralStateTests/stAttackTest", ] RSpec.describe Ciri::EVM do before(:all) do prepare_ethereum_fixtures end def parse_account(v) balance = Ciri::Utils.dehex_number(v["balance"]) nonce = Ciri::Utils.dehex_number(v["nonce"]) code = Ciri::Utils.dehex(v["code"]) storage = v["storage"].map do |k, v| [Ciri::Utils.dehex_number(k), Ciri::Utils.dehex_number(v)] end.to_h [Ciri::Types::Account.new(balance: balance, nonce: nonce), code, storage] end def build_transaction(transaction_data, args) key = Ciri::Key.from_private_key(Ciri::Utils.dehex(transaction_data['secretKey'])) transaction = Ciri::POWChain::Transaction.new( data: Ciri::Utils.dehex(transaction_data['data'][args['data']]), gas_limit: Ciri::Utils.dehex_number(transaction_data['gasLimit'][args['gas']]), gas_price: Ciri::Utils.dehex_number(transaction_data['gasPrice']), nonce: Ciri::Utils.dehex_number(transaction_data['nonce']), to: Ciri::Types::Address.new(Ciri::Utils.dehex(transaction_data['to'])), value: Ciri::Utils.dehex_number(transaction_data['value'][args['value']]) ) transaction.sign_with_key!(key) transaction end def choose_fork_schema(fork_name) case fork_name when 'Frontier' Ciri::Forks::Frontier::Schema.new when 'Homestead' Ciri::Forks::Homestead::Schema.new(support_dao_fork: false) when 'EIP150' Ciri::Forks::TangerineWhistle::Schema.new when 'EIP158' Ciri::Forks::SpuriousDragon::Schema.new when 'Byzantium' Ciri::Forks::Byzantium::Schema.new when 'Constantinople' Ciri::Forks::Constantinople::Schema.new else raise ArgumentError.new("unknown fork #{fork_name}") end end def self.block_info_from_env(env) return nil unless env Ciri::EVM::BlockInfo.new( coinbase: Ciri::Utils.dehex(env['currentCoinbase']), difficulty: env['currentDifficulty'].to_i(16), gas_limit: env['currentGasLimit'].to_i(16), number: env['currentNumber'].to_i(16), timestamp: env['currentTimestamp'].to_i(16), ) end def prepare_state(state, fixture) fixture['pre'].each do |address, v| address = Ciri::Types::Address.new Ciri::Utils.dehex(address) account, code, storage = parse_account(v) state.set_balance(address, account.balance) state.set_nonce(address, account.nonce) state.set_account_code(address, code) storage.each do |key, value| state.store(address, key, value) end end end def self.run_test_case(test_case, prefix: nil, tags: ) test_case.each do |name, t| context "#{prefix} #{name}", **tags do block_info = block_info_from_env(t['env']) t['post'].each do |fork_name, configs| it fork_name, **tags do fork_schema = choose_fork_schema(fork_name) configs.each do |config| db = Ciri::DB::Backend::Memory.new state = Ciri::State.new(db) prepare_state(state, t) indexes = config['indexes'] transaction = build_transaction(t['transaction'], indexes) transaction.sender evm = Ciri::EVM.new(state: state, fork_schema: fork_schema) result = begin evm.execute_transaction(transaction, block_info: block_info, ignore_exception: true) rescue StandardError Ciri::EVM::ExecutionResult.new(logs: []) end if config['logs'] expect(Ciri::Utils.hex result.logs_hash).to eq config['logs'] end end end end end end end Dir.glob("fixtures/GeneralStateTests/*").each do |topic| tags = SLOW_TOPIC.include?(topic) ? {slow: true} : {} Dir.glob("#{topic}/*.json").each do |t| run_test_case(JSON.load(open t), prefix: topic, tags: tags) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/db/account_db_spec.rb
spec/ciri/db/account_db_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/db/account_db' require 'ciri/rlp' require 'ciri/utils' # copy from https://github.com/ethereum/py-trie/blob/master/tests/test_proof.py RSpec.describe Ciri::DB::AccountDB do let(:account1) do [Ciri::Utils.dehex('0x8888f1f195afa192cfee860698584c030f4c9db1'), Ciri::Types::Account.new_empty] end it 'find_account' do address, account = account1 account.nonce = 3 account_db = Ciri::DB::AccountDB.new({}) account_db.set_nonce(address, account.nonce) expect(account_db.find_account(address)).to eq account end it 'store' do address, _account = account1 account_db = Ciri::DB::AccountDB.new({}) account_db.store(address, 42, 1530984410) expect(account_db.fetch(address, 42)).to eq 1530984410 end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/db/kv_db_spec.rb
spec/ciri/db/kv_db_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'fileutils' require 'ciri/db/backend/memory' require 'ciri/db/backend/rocks' RSpec.describe Ciri::DB::Backend do let(:tmp_dir) {Dir.mktmpdir} let(:rocks_db) {Ciri::DB::Backend::Rocks.new(tmp_dir)} let(:memory_db) {Ciri::DB::Backend::Memory.new} let(:stores) {[memory_db, rocks_db]} after do rocks_db.close FileUtils.remove_entry tmp_dir end it 'basic store' do stores.each do |store| store.put "one", "1" store["two"] = "2" expect(store["one"]).to eq "1" expect(store.get("two")).to eq "2" expect(store.get("three")).to be_nil expect(store.fetch("two")).to eq "2" expect {store.fetch("three")}.to raise_error(KeyError) end end it 'delete & include?' do stores.each do |store| store.put "one", "1" store["two"] = "2" expect(store.include?("one")).to be_truthy expect(store.include?("two")).to be_truthy store.delete("two") expect(store.include?("one")).to be_truthy expect(store.include?("two")).to be_falsey expect(store.get("two")).to be_nil expect {store.fetch("two")}.to raise_error(KeyError) end end it 'batch' do stores.each do |store| store.batch do |b| b.put "a", "1" b.put "b", "2" end expect(["a", "b"].map {|k| store[k]}).to eq ["1", "2"] expect do store.batch do |b| b.put "c", "1" raise StandardError.new("winter is coming") b.put "d", "2" end end.to raise_error(StandardError, 'winter is coming') expect(["a", "b", "c", "d"].map {|k| store[k]}).to eq ["1", "2", nil, nil] end end it 'closed' do stores.each do |store| expect(store.closed?).to be_falsey expect(store.close).to be_nil expect(store.closed?).to be_truthy expect do store["eh?"] end.to raise_error(Ciri::DB::Backend::InvalidError) end end it 'handle null byte string' do stores.each do |store| store.put "onetwo", "1\u00002" expect(store["onetwo"]).to eq "1\u00002" store.put "1\u00002", "onetwo" expect(store["1\u00002"]).to eq "onetwo" end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/db/backend/rocks_spec.rb
spec/ciri/db/backend/rocks_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'fileutils' require 'ciri/db/backend/rocks' RSpec.describe Ciri::DB::Backend::Rocks do let(:tmp_dir) {Dir.mktmpdir} let(:store) {Ciri::DB::Backend::Rocks.new(tmp_dir)} after do store.close FileUtils.remove_entry tmp_dir end it 'basic store' do store.put "one", "1" store["two"] = "2" expect(store["one"]).to eq "1" expect(store.get("two")).to eq "2" expect(store.get("three")).to be_nil expect(store.keys.to_a).to eq ["one", "two"] values = [] store.keys.each {|i| values << i} expect(values).to eq ["one", "two"] expect(store.each.to_a).to eq [["one", "1"], ["two", "2"]] end it 'scan' do store["apple"] = "1" store["banana"] = "2" store["pineapple"] = "3" store["pen"] = "4" expect(store.scan("p").to_a).to eq [["pen", "4"], ["pineapple", "3"]] expect(store.scan("pe").to_a).to eq [["pen", "4"], ["pineapple", "3"]] expect(store.scan("pi").to_a).to eq [["pineapple", "3"]] end it 'batch' do store.batch do |b| b.put "a", "1" b.put "b", "2" end expect(store.keys.to_a).to eq ["a", "b"] expect do store.batch do |b| b.put "c", "1" raise StandardError.new("winter is coming") b.put "d", "2" end end.to raise_error(StandardError, 'winter is coming') expect(store.keys.to_a).to eq ["a", "b"] end it 'closed' do expect(store.closed?).to be_falsey expect(store.close).to be_nil expect(store.closed?).to be_truthy expect do store["eh?"] end.to raise_error(Ciri::DB::Backend::InvalidError) end it 'handle null byte string' do store.put "onetwo", "1\u00002" expect(store["onetwo"]).to eq "1\u00002" store.put "1\u00002", "onetwo" expect(store["1\u00002"]).to eq "onetwo" end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/pow_chain/chain_spec.rb
spec/ciri/pow_chain/chain_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/db/backend/memory' require 'ciri/pow_chain/chain' require 'ciri/utils' RSpec.describe Ciri::POWChain::Chain do let(:store) {Ciri::DB::Backend::Memory.new} let(:fork_config) {Ciri::Forks::Config.new([[0, Ciri::Forks::Frontier::Schema.new]])} context Ciri::POWChain::HeaderChain do let(:header_chain) {Ciri::POWChain::HeaderChain.new(store, fork_config: fork_config)} let(:headers) do load_blocks('blocks').map(&:header) end it 'get/set head' do header_chain.head = headers[0] expect(header_chain.head).to eq headers[0] end it 'write and get' do header_chain.write headers[0] header_chain.write headers[1] expect(header_chain.get_header(headers[0].get_hash)).to eq headers[0] expect(header_chain.get_header(headers[1].get_hash)).to eq headers[1] # also write total difficulty expect(header_chain.total_difficulty(headers[0].get_hash)).to eq headers[0].difficulty expect(header_chain.total_difficulty(headers[1].get_hash)).to eq headers[0].difficulty + headers[1].difficulty end it 'write and get number' do header_chain.write_header_hash_number headers[0].get_hash, 0 header_chain.write_header_hash_number headers[1].get_hash, 1 expect(header_chain.get_header_hash_by_number(0)).to eq headers[0].get_hash expect(header_chain.get_header_hash_by_number(1)).to eq headers[1].get_hash end it 'valid?' do # fail, cause no parent exist expect(header_chain.valid? headers[1]).to be_falsey # timestamp not correct header = headers[1].dup header.timestamp = headers[0].timestamp expect(header_chain.valid? header).to be_falsey # height not correct header = headers[1].dup header.number += 1 expect(header_chain.valid? header).to be_falsey # gas limit not correct header = headers[1].dup header.gas_limit = 5001 expect(header_chain.valid? header).to be_falsey # pass valid! header_chain.write headers[0] expect(header_chain.valid? headers[1]).to be_truthy end end context Ciri::POWChain::Chain do let(:blocks) do load_blocks('blocks') end let(:chain) {Ciri::POWChain::Chain.new(store, genesis: blocks[0], network_id: 0, fork_config: fork_config)} it 'genesis is current block' do expect(chain.genesis_hash).to eq chain.current_block.header.get_hash end it 'insert wrong order blocks' do expect do chain.insert_blocks(blocks[1..2].reverse) end.to raise_error Ciri::POWChain::Chain::InvalidBlockError end it 'insert blocks' do chain.insert_blocks(blocks[1..2], validate: false) expect(chain.get_block_by_number(1)).to eq blocks[1] expect(chain.get_block_by_number(2)).to eq blocks[2] expect(chain.current_block).to eq blocks[2] end context 'when forked chain beyond main chain' do let(:main_chain_blocks) do load_blocks('chain_fork/main_chain') end let(:forked_chain_blocks) do load_blocks('chain_fork/forked_chain') end let(:chain) {Ciri::POWChain::Chain.new(store, genesis: main_chain_blocks[0], network_id: 0, fork_config: fork_config)} it 'forked blocks should reorg current chain' do # initial main chain chain.insert_blocks(main_chain_blocks[1..-1], validate: false) td = chain.total_difficulty current_block = chain.current_block expect(current_block).to eq main_chain_blocks.last chain.current_block.number.times do |i| expect(chain.get_block_by_number(i)).to eq main_chain_blocks[i] end # receive forked chain chain.insert_blocks(forked_chain_blocks[1..-1], validate: false) expect(chain.total_difficulty).to be > td expect(chain.current_block).to_not eq current_block expect(chain.current_block).to eq forked_chain_blocks.last chain.current_block.number.times do |i| expect(chain.get_block_by_number(i)).to eq forked_chain_blocks[i] end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/pow_chain/pow_spec.rb
spec/ciri/pow_chain/pow_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/pow_chain/pow' require 'ciri/utils' RSpec.describe Ciri::POWChain::POW do it 'check_pow' do block_number = 1 mining = Ciri::Utils.dehex '85913a3057ea8bec78cd916871ca73802e77724e014dda65add3405d02240eb7' mix_hash = Ciri::Utils.dehex('0x969b900de27b6ac6a67742365dd65f55a0526c41fd18e1b16f1a1215c2e66f59') nonce = Ciri::Utils.dehex('0x539bd4979fef1ec4') difficulty = 17171480576 # not satisfy difficulty expect do Ciri::POWChain::POW.check_pow(block_number, mining, mix_hash, nonce, 2 ** 256) end.to raise_error(Ciri::POWChain::POW::InvalidError) # not satisfy mix_hash expect do Ciri::POWChain::POW.check_pow(block_number, mining, "\x00".b * 32, nonce, difficulty) end.to raise_error(Ciri::POWChain::POW::InvalidError) expect do Ciri::POWChain::POW.check_pow(block_number, mining, mix_hash, nonce, difficulty) end.to_not raise_error end it 'mine_pow_nonce' do block_number = 42 mining = "\x00".b * 32 difficulty = 1 mix_hash, nonce = Ciri::POWChain::POW.mine_pow_nonce(block_number, mining, difficulty) expect do Ciri::POWChain::POW.check_pow(block_number, mining, mix_hash, nonce, difficulty) end.to_not raise_error end context 'check pow_chain with real blocks' do let(:blocks) {load_blocks('blocks')} it 'check blocks pow_chain' do blocks[1..5].each do |block| block_number = block.header.number mining = block.header.mining_hash mix_hash = block.header.mix_hash nonce = block.header.nonce difficulty = block.header.difficulty expect do Ciri::POWChain::POW.check_pow(block_number, mining, mix_hash, nonce, difficulty) end.to_not raise_error end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/pow_chain/chain/header_spec.rb
spec/ciri/pow_chain/chain/header_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/pow_chain/header' require 'ciri/utils' RSpec.describe Ciri::POWChain::Header do it 'compute header hash' do raw_header_rlp = 'f90218a0d33c9dde9fff0ebaa6e71e8b26d2bda15ccf111c7af1b633698ac847667f0fb4a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d493479452bc44d5378309ee2abf1539bf71de1b7d7be3b5a0ed98aa4b5b19c82fb35364f08508ae0a6dec665fa57663dca94c5d70554cde10a0447cbd8c48f498a6912b10831cdff59c7fbfcbbe735ca92883d4fa06dcd7ae54a07fa0f6ca2a01823208d80801edad37e3e3a003b55c89319b45eb1f97862ad229b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000860b6b4beb1e8e830f423f832fefd8830386588456bfb40598d783010303844765746887676f312e342e32856c696e7578a05b10f4a08a6c209d426f6158bd24b574f4f7b7aa0099c67c14a1f693b4dd04d088f491f46b60fe04b3' header_hash = Ciri::Utils.dehex 'b4fbadf8ea452b139718e2700dc1135cfc81145031c84b7ab27cd710394f7b38' # get binary version raw_header_rlp_b = Ciri::Utils.dehex raw_header_rlp header = Ciri::POWChain::Header.rlp_decode(raw_header_rlp_b) expect(header.get_hash).to eq header_hash end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/pow_chain/chain/transaction_spec.rb
spec/ciri/pow_chain/chain/transaction_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/pow_chain/transaction' require 'ciri/key' RSpec.describe Ciri::POWChain::Transaction do it 'sign' do t = Ciri::POWChain::Transaction.new(nonce: 1, gas_price: 1, gas_limit: 5, to: 0x00, value: 0) key = Ciri::Key.random t.sign_with_key! key expect(t.sender.to_s).to eq Ciri::Utils.keccak(key.raw_public_key[1..-1])[-20..-1] end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/beacon_chain/block_spec.rb
spec/ciri/beacon_chain/block_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/beacon_chain/block' RSpec.describe Ciri::BeaconChain::Block do it 'new' do block = described_class.new( parent_hash: Ciri::Types::Hash32.new("\x01".b * 32), slot_number: 1, randao_reveal: Ciri::Types::Hash32.new("\x99".b * 32), attestations: [], pow_chain_ref: Ciri::Types::Hash32.new("\x51".b * 32), active_state_root: Ciri::Types::Hash32.new("\x00".b * 32), crystallized_state_root: Ciri::Types::Hash32.new("\x11".b * 32), ) decoded_block = described_class.rlp_decode described_class.rlp_encode(block) expect(block).to eq decoded_block end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/eth/protocol_messages_spec.rb
spec/ciri/eth/protocol_messages_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/eth/protocol_messages' require 'ciri/utils' RSpec.describe Ciri::Eth::BlockBodies do it Ciri::Eth::HashOrNumber do encoded = Ciri::Eth::HashOrNumber.rlp_encode Ciri::Eth::HashOrNumber.new(42) expect(Ciri::Eth::HashOrNumber.rlp_decode(encoded)).to eq 42 hash = "\x02".b * 32 encoded = Ciri::Eth::HashOrNumber.rlp_encode Ciri::Eth::HashOrNumber.new(hash) expect(Ciri::Eth::HashOrNumber.rlp_decode(encoded)).to eq hash end it 'decode block bodies message' do payload = Ciri::Utils.dehex 'f904cdf904caf904c6f86e8201d3850df84758008252089432be343b94f860124dc4fee278fdcbd38c102d8888102363ac310a4000801ca043531017f1569ec692c0bf1ad710ddb5158b60505ea33fb7a21245738539e2d5a03856c6a1117ff71e9b769ccb6960674038a3326c3dd84c152fc83ada28145a07f86c09850df84758008252089432be343b94f860124dc4fee278fdcbd38c102d88880ed350879ce50000801ba08219a4f30cb8dd7d5e1163ac433f207b599d804b0d74ee54c8694014db647700a03db2e806986a746d44d675fdbbd7594bb2856946ba257209abfffdd1628141aff86c59850df84758008252089432be343b94f860124dc4fee278fdcbd38c102d88882b0ca8b9f5f02000801ba01ca26859a6eed116312010359c2e8351d126f31b078a0e2e19aae0acc98d9488a0172c1a299737440a9063af6547d567ca7d269bfc2a9e81ec1de21aa8bd8e17b1f86c02850df84758008252089432be343b94f860124dc4fee278fdcbd38c102d88880fd037ba87693800801ba00a5aca100a264a8da4a58bef77c5116a6dde42186ac249623c0edcb30189640aa0783e9439755023b919897574f94337aaac4a1ddc20217e3ac264a7edf813ffddf86d81d9850df84758008252089432be343b94f860124dc4fee278fdcbd38c102d888814bac05c835a5400801ba00b93c6f8dce800a1ec57d70813c4d35e3ffe25a6f1ae9057cf706636cf34d662a06d254a5557b7716ef01dd28aa84cc919f397c0a778f3a109a1ee9df2fc530ec0f86c34850df84758008252089432be343b94f860124dc4fee278fdcbd38c102d88880f258512af0d4000801ba0e9a25c929c26d1a95232ba75aef419a91b470651eb77614695e16c5ba023e383a0679fb2fc0d0b0f3549967c0894ee7d947f07d238a83ef745bc3ced5143a4af36f86c6f850df84758008252089432be343b94f860124dc4fee278fdcbd38c102d88881c54e302456eb400801ca09e0b8360a36d6d0320aef19bd811431b1a692504549da9f05f9b4d9e329993b9a05acff70bd8cf82d9d70b11d4e59dc5d54937475ec394ec846263495f61e5e6eef86c46850df84758008252089432be343b94f860124dc4fee278fdcbd38c102d88880f0447b1edca4000801ca0b2803f1bfa237bda762d214f71a4c71a7306f55df2880c77d746024e81ccbaa2a07aeed35c0cbfbe0ed6552fd55b3f57fdc054eeabd02fc61bf66d9a8843aa593af86d03850ba43b740083015f909426016a2b5d872adc1b131a4cd9d4b18789d0d9eb88016345785d8a0000801ba06dccb1349919662c40455aee04472ae307195580837510ecf2e6fc428876eb03a03b84ea9c3c6462ac086a1d789a167c2735896a6b5a40e85a6e45da8884fe27def8708302a11f850ba43b740083015f90945275c3371ece4d4a5b1e14cf6dbfc2277d58ef92880e93ea6a35f2e000801ba0aa8909295ff178639df961126970f44b5d894326eb47cead161f6910799a98b8a0254d7742eccaf2f4c44bfe638378dcf42bdde9465f231b89003cc7927de5d46ef8708302a120850ba43b740083015f90941c51bf013add0857c5d9cf2f71a7f15ca93d4816880e917c4b10c87400801ca0cfe3ad31d6612f8d787c45f115cc5b43fb22bcc210b62ae71dc7cbf0a6bea8dfa057db8998114fae3c337e99dbd8573d4085691880f4576c6c1f6c5bbfe67d6cf0c0' block_bodies = Ciri::Eth::BlockBodies.rlp_decode(payload) expect(block_bodies.bodies.size).to eq 1 expect(block_bodies.bodies[0].transactions.size).to eq 11 end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/spec/ciri/eth/eth_protocol_spec.rb
spec/ciri/eth/eth_protocol_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'async/queue' require 'ciri/eth/eth_protocol' require 'ciri/p2p/rlpx' require 'ciri/p2p/node' require 'ciri/p2p/peer' require 'ciri/p2p/peer_store' require 'ciri/p2p/protocol' require 'ciri/p2p/protocol_io' require 'ciri/p2p/network_state' require 'ciri/pow_chain/chain' require 'ciri/db/backend/rocks' require 'ciri/key' RSpec.describe Ciri::Eth::EthProtocol do context 'syncing' do let(:blocks) do load_blocks('blocks') end let(:tmp_dir) {Dir.mktmpdir} let(:store) {Ciri::DB::Backend::Rocks.new tmp_dir} let(:fork_config) {Ciri::Forks::Config.new([[0, Ciri::Forks::Frontier::Schema.new]])} let(:chain) {Ciri::POWChain::Chain.new(store, genesis: blocks[0], network_id: 0, fork_config: fork_config)} let(:peer_store) { Ciri::P2P::PeerStore.new } after do # clear db store.close FileUtils.remove_entry tmp_dir end # a fake frame_io to simulate the connection let(:mock_frame_io) do Class.new do def initialize(read:, write:, name: '') @read = read @write = write @name = name end def send_data(code, data) msg = Ciri::P2P::RLPX::Message.new(code: code, size: data.size, payload: data) write_msg(msg) end def write_msg(msg) content = msg.rlp_encode @write.enqueue "#{content.length};#{content}" end def read_msg io = StringIO.new(@read.dequeue) len = io.readline(sep = ';').to_i Ciri::P2P::RLPX::Message.rlp_decode io.read(len) end end end def send_data(queue, code, data) msg = Ciri::P2P::RLPX::Message.new(code: code, size: data.size, payload: data) queue.enqueue msg end def read_msg(queue) queue.dequeue end it 'handle eth protocol, and start syncing blocks' do eth_protocol = Ciri::Eth::EthProtocol.new(name: 'eth', version: 63, length: 17, chain: chain) message_queue = Async::Queue.new receive_queue = Async::Queue.new allow_any_instance_of(Ciri::P2P::ProtocolContext).to receive(:send_data) do |receiver, code, data| msg = Ciri::P2P::RLPX::Message.new(code: code, size: data.size, payload: data) receive_queue.enqueue(msg) end caps = [Ciri::P2P::RLPX::Cap.new(name: 'eth', version: 63)] peer_id = Ciri::Key.random.raw_public_key[1..-1] hs = Ciri::P2P::RLPX::ProtocolHandshake.new(version: 0, name: 'test', caps: caps, listen_port: 30303, id: peer_id) peer = Ciri::P2P::Peer.new(nil, hs, [], direction: :inbound) Async::Reactor.run do |task| # start eth protocol task.async do context = Ciri::P2P::ProtocolContext.new(nil, peer: peer) peer = nil eth_protocol.initialized(context) eth_protocol.connected(context) while (msg = message_queue.dequeue) eth_protocol.received(context, msg) end eth_protocol.disconnected(context) end # our test cases task.async do |task| # receive status from peer status = Ciri::Eth::Status.rlp_decode read_msg(receive_queue).payload expect(status.network_id).to eq 1 expect(status.total_difficulty).to eq chain.total_difficulty expect(status.genesis_block).to eq chain.genesis.get_hash # send status to peer status = Ciri::Eth::Status.new( protocol_version: status.protocol_version, network_id: status.network_id, total_difficulty: 68669161470, current_block: blocks[3].get_hash, genesis_block: status.genesis_block) send_data(message_queue, Ciri::Eth::Status::CODE, status.rlp_encode) # should receive get_header msg = read_msg(receive_queue) get_block_bodies = Ciri::Eth::GetBlockHeaders.rlp_decode msg.payload # peer should request for current head expect(get_block_bodies.hash_or_number).to eq blocks[3].get_hash block_headers = Ciri::Eth::BlockHeaders.new(headers: [blocks[3].header]) send_data(message_queue, Ciri::Eth::BlockHeaders::CODE, block_headers.rlp_encode) # simulate peer actions, until peer synced latest block last_header = loop do get_block_bodies = Ciri::Eth::GetBlockHeaders.new(hash_or_number: Ciri::Eth::HashOrNumber.new(3), amount: 1, skip: 0, reverse: false) send_data(message_queue, Ciri::Eth::GetBlockHeaders::CODE, get_block_bodies.rlp_encode) msg = read_msg(receive_queue) case msg.code when Ciri::Eth::GetBlockHeaders::CODE get_block_bodies = Ciri::Eth::GetBlockHeaders.rlp_decode msg.payload block = blocks.find {|b| b.get_hash == get_block_bodies.hash_or_number || b.number == get_block_bodies.hash_or_number} headers = block ? [block.header] : [] block_headers = Ciri::Eth::BlockHeaders.new(headers: headers) send_data(message_queue, Ciri::Eth::BlockHeaders::CODE, block_headers.rlp_encode) when Ciri::Eth::GetBlockBodies::CODE get_block_bodies = Ciri::Eth::GetBlockBodies.rlp_decode msg.payload bodies = [] get_block_bodies.hashes.each do |hash| b = blocks.find {|b| hash == b.get_hash} bodies << Ciri::Eth::BlockBodies::Bodies.new(transactions: b.transactions, ommers: b.ommers) end block_bodies = Ciri::Eth::BlockBodies.new(bodies: bodies) send_data(message_queue, Ciri::Eth::BlockBodies::CODE, block_bodies.rlp_encode) when Ciri::Eth::BlockHeaders::CODE block_headers = Ciri::Eth::BlockHeaders.rlp_decode msg.payload break block_headers.headers[0] if !block_headers.headers.empty? && block_headers.headers[0].number == 3 else raise "unknown code #{msg.code}" end end expect(last_header).to eq blocks[3].header # A hack to cancel timers from reactor, so we don't need to wait for timers task.reactor.instance_variable_get(:@timers).cancel task.reactor.stop end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/examples/sign_transaction.rb
examples/sign_transaction.rb
require 'ciri' require 'ciri/pow_chain/transaction' require 'ciri/key' require 'ciri/utils' include Ciri transaction = POWChain::Transaction.new( nonce: 1, gas_price: 10, gas_limit: 21000, to: "\x00".b * 20, value: 10 ** 18 ) # generate sender priv_key priv_key = Key.random # sign transaction transaction.sign_with_key!(priv_key) sender = Utils.hex(transaction.sender) puts "#{sender}\n-> send #{transaction.value} to\n#{Utils.hex transaction.to}"
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/examples/invoke_evm.rb
examples/invoke_evm.rb
require 'ciri' require 'ciri/pow_chain/transaction' require 'ciri/forks/byzantium' require 'ciri/key' require 'ciri/state' require 'ciri/evm' require 'ciri/evm/block_info' require 'ciri/db/backend/memory' require 'ciri/utils/logger' require 'ciri/utils' include Ciri Utils::Logger.setup(level: :info) # bytecode of ballot contract, copy from remix example BALLOT_BYTECODE = Utils.dehex "608060405234801561001057600080fd5b50604051602080610487833981016040908152905160008054600160a060020a0319163317808255600160a060020a03168152600160208190529290209190915560ff8116610060600282610067565b50506100b1565b81548183558181111561008b5760008381526020902061008b918101908301610090565b505050565b6100ae91905b808211156100aa5760008155600101610096565b5090565b90565b6103c7806100c06000396000f3006080604052600436106100615763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416635c19a95c8114610066578063609ff1bd146100895780639e7b8d61146100b4578063b3f98adc146100d5575b600080fd5b34801561007257600080fd5b50610087600160a060020a03600435166100f0565b005b34801561009557600080fd5b5061009e610250565b6040805160ff9092168252519081900360200190f35b3480156100c057600080fd5b50610087600160a060020a03600435166102bb565b3480156100e157600080fd5b5061008760ff6004351661031b565b33600090815260016020819052604082209081015490919060ff16156101155761024b565b5b600160a060020a0383811660009081526001602081905260409091200154620100009004161580159061016d5750600160a060020a0383811660009081526001602081905260409091200154620100009004163314155b1561019f57600160a060020a039283166000908152600160208190526040909120015462010000900490921691610116565b600160a060020a0383163314156101b55761024b565b506001818101805460ff1916821775ffffffffffffffffffffffffffffffffffffffff0000191662010000600160a060020a0386169081029190911790915560009081526020829052604090209081015460ff16156102435781546001820154600280549091610100900460ff1690811061022c57fe5b60009182526020909120018054909101905561024b565b815481540181555b505050565b600080805b60025460ff821610156102b6578160028260ff1681548110151561027557fe5b906000526020600020016000015411156102ae576002805460ff831690811061029a57fe5b906000526020600020016000015491508092505b600101610255565b505090565b600054600160a060020a0316331415806102f15750600160a060020a0381166000908152600160208190526040909120015460ff165b156102fb57610318565b600160a060020a0381166000908152600160208190526040909120555b50565b3360009081526001602081905260409091209081015460ff1680610344575060025460ff831610155b1561034e57610397565b6001818101805460ff191690911761ff00191661010060ff85169081029190911790915581546002805491929091811061038457fe5b6000918252602090912001805490910190555b50505600a165627a7a723058200864fb02ff362bbc06e105162a9fcbfe289feff2354dbe84cf794f1fb2ec38d60029" # generate a contract creation transaction priv_key = Key.random transaction = POWChain::Transaction.new( nonce: 1, gas_price: 10, gas_limit: 3000000, to: '', value: 0, data: BALLOT_BYTECODE ) transaction.sign_with_key!(priv_key) # prepare some eth to sender account state = State.new(DB::Backend::Memory.new) state.add_balance(transaction.sender, 10 ** 18) block_info = EVM::BlockInfo.new( coinbase: "\x00".b * 20, ) evm = EVM.new(state: state, fork_schema: Ciri::Forks::Byzantium::Schema.new) result = evm.execute_transaction(transaction, block_info: block_info) puts "Ballot contract transaction\n---------" puts "sender:#{Utils.hex transaction.sender}\n-> send #{transaction.value} value to\nto:#{Utils.hex transaction.to}\ndata(#{transaction.data.size} bytes)" puts "\nEVM executing ->\n\n" puts "Execution result\n---------" if result.status == 0 puts "Transaction failed" exit 1 end material = RLP.encode_simple([transaction.sender.to_s, transaction.nonce]) contract_address = Utils.keccak(material)[-20..-1] puts "Transaction success!!" puts "Gas Used: #{result.gas_used}" puts "State root: #{Utils.hex result.state_root}" puts "Contract created at: #{Utils.hex contract_address}" puts "Contract data(#{result.output.size} bytes)"
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/examples/sync_blocks/sync.rb
examples/sync_blocks/sync.rb
require 'ciri/utils' require 'ciri/key' require 'ciri/rlp' require 'ciri/eth' require 'ciri/evm' require 'ciri/p2p/address' require 'ciri/p2p/server' require 'ciri/p2p/rlpx' require 'ciri/p2p/protocol' require 'ciri/pow_chain/chain' require 'ciri/forks/frontier' require 'ciri/db/backend/rocks' require 'logger' require 'yaml' require 'pp' include Ciri Utils::Logger.setup(level: :debug) def read_genesis_block(path) genesis_info = YAML.load open(path).read genesis_info = genesis_info.map {|k, v| [k.to_sym, v]}.to_h %i{extra_data logs_bloom beneficiary mix_hash nonce parent_hash receipts_root ommers_hash state_root transactions_root}.each do |i| genesis_info[i] = Utils.dehex(genesis_info[i]) end transactions = genesis_info.delete(:transactions) ommers = genesis_info.delete(:ommers) header = POWChain::Header.new(**genesis_info) POWChain::Block.new(header: header, transactions: transactions, ommers: ommers) end def get_target_node if ARGV.size != 1 puts "Usage: ruby examples/sync_blocks/sync.rb <node_id>" exit(1) end node_url = ARGV[0] Ciri::P2P::Node.parse(node_url) end # init genesis block genesis = read_genesis_block("#{__dir__}/genesis.yaml") puts "read genesis:" pp genesis.header.inspect db = DB::Backend::Rocks.new('tmp/test_db') fork_config = Forks::Config.new([[0, Forks::Frontier], [1150000, Forks::Homestead], [4370000, Forks::Byzantium]]) chain = POWChain::Chain.new(db, genesis: genesis, network_id: 1, fork_config: fork_config) # init eth protocol eth_protocol = Eth::EthProtocol.new(name: 'eth', version: 63, length: 17, chain: chain) # init node bootnodes = [get_target_node] # init server private_key = Ciri::Key.random server = Ciri::P2P::Server.new(private_key: private_key, protocols: [eth_protocol], bootnodes: bootnodes, tcp_port: 0, udp_port: 0) puts "start syncing server" server.run
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-utils/spec/spec_helper.rb
ciri-utils/spec/spec_helper.rb
require "bundler/setup" require "ciri/utils" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-utils/spec/ciri/utils_spec.rb
ciri-utils/spec/ciri/utils_spec.rb
RSpec.describe Ciri::Utils do it "has a version number" do expect(Ciri::Utils::VERSION).not_to be nil end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-utils/spec/ciri/utils/logger_spec.rb
ciri-utils/spec/ciri/utils/logger_spec.rb
require 'ciri/utils/logger' RSpec.describe Ciri::Utils::Logger do let(:logger) do Class.new do include Ciri::Utils::Logger def log_info(msg) info(msg) end end end it "output null without setup" do expect(Ciri::Utils::Logger.global_logger).to be_nil expect do logger.log_info("hello") end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-utils/lib/ciri/utils.rb
ciri-utils/lib/ciri/utils.rb
require "ciri/utils/version" require 'digest/sha3' require_relative 'utils/number' module Ciri module Utils class << self include Utils::Number def keccak(*data, bits: 256) s = Digest::SHA3.new(bits) data.each {|i| s.update(i)} s.digest end def secret_compare(s1, s2) s1.size == s2.size && s1.each_byte.each_with_index.map {|b, i| b ^ s2[i].ord}.reduce(0, :+) == 0 end def hex(data) hex = data.to_s.unpack("H*").first '0x' + hex end def dehex(hex) hex = hex[2..-1] if hex.start_with?('0x') [hex].pack("H*") end def dehex_number(hexed_number) big_endian_decode dehex(hexed_number) end def hex_number(number) hex big_endian_encode(number) end def create_ec_pk(raw_pubkey: nil, raw_privkey: nil) public_key = raw_pubkey && begin group = OpenSSL::PKey::EC::Group.new('secp256k1') bn = OpenSSL::BN.new(raw_pubkey, 2) OpenSSL::PKey::EC::Point.new(group, bn) end OpenSSL::PKey::EC.new('secp256k1').tap do |key| key.public_key = public_key if public_key key.private_key = OpenSSL::BN.new(raw_privkey, 2) if raw_privkey end end def to_underscore(str) str.gsub(/[A-Z]/) {|a| "_" + a.downcase} end def blank_bytes?(item) return true if item.is_a?(String) && item.each_byte.all?(&:zero?) blank?(item) end def blank?(item) if item.nil? true elsif item.is_a? Integer item.zero? elsif item.is_a? String item.empty? else false end end def present?(item) !blank?(item) end end BLANK_SHA3 = Utils.keccak(''.b).freeze end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-utils/lib/ciri/utils/version.rb
ciri-utils/lib/ciri/utils/version.rb
module Ciri module Utils VERSION = "0.2.2" end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-utils/lib/ciri/utils/logger.rb
ciri-utils/lib/ciri/utils/logger.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'logger' module Ciri module Utils # Logger # Example: # # class A # include Logger # # def initialize(name) # @name = name # debug("initial with name") # end # # def greet # puts "hello" # debug("greeting hello") # end # # # customize logging name # def logging_name # "#{super}:#{@name}" # end # end # # # don't forget initialize global logger # Ciri::Utils::Logger.setup(level: :debug) # module Logger class << self attr_reader :global_logger def setup(level:) @global_logger = ::Logger.new(STDERR, level: level) global_logger.datetime_format = '%Y-%m-%d %H:%M:%S' end end protected def debug(message) add(::Logger::DEBUG, message) end def info(message) add(::Logger::INFO, message) end def error(message) add(::Logger::ERROR, message) end def logging_name self.class.to_s end private def add(severity, message = nil, progname = logging_name) Logger.global_logger&.add(severity, message, progname) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-utils/lib/ciri/utils/number.rb
ciri-utils/lib/ciri/utils/number.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri module Utils module Number extend self def big_endian_encode(n, zero = ''.b, size: nil) b = big_endian_encode_raw(n, zero) size.nil? ? b : b.rjust(size, "\x00".b) end def big_endian_decode(input) input.each_byte.reduce(0) {|s, i| s * 256 + i} end UINT_256_MAX = 2 ** 256 - 1 UINT_256_CEILING = 2 ** 256 UINT_255_MAX = 2 ** 255 - 1 UINT_255_CEILING = 2 ** 255 def unsigned_to_signed(n) n <= UINT_255_MAX ? n : n - UINT_256_CEILING end def signed_to_unsigned(n) n >= 0 ? n : n + UINT_256_CEILING end def ceil_div(n, ceil) size, m = n.divmod ceil m.zero? ? size : size + 1 end private def big_endian_encode_raw(n, zero = ''.b) if n == 0 zero elsif n > 0 big_endian_encode(n / 256) + (n % 256).chr else raise ArgumentError.new("can't encode negative number #{n}") end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri.rb
lib/ciri.rb
# Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require "ciri/version" module Ciri # Your code goes here... end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/eth.rb
lib/ciri/eth.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'eth/protocol_messages' require_relative 'eth/eth_protocol' module Ciri # implement Ethereum Wire Protocol # https://github.com/ethereum/wiki/wiki/Ethereum-Wire-Protocol module Eth end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/trie.rb
lib/ciri/trie.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils' require 'ciri/rlp' require_relative 'trie/nodes' module Ciri # copy py-trie implementation https://github.com/ethereum/py-trie/ class Trie class BadProofError < StandardError end class << self def proof(root_hash, key, proofs) proof_nodes = proofs.map {|n| n.is_a?(Trie::Node) ? n : Trie::Node.decode(n)} proof_with_nodes(root_hash, key, proof_nodes) end def proof_with_nodes(root_hash, key, proof_nodes) trie = new proof_nodes.each do |node| trie.persist_node(node) end trie.root_hash = root_hash begin result = trie.fetch(key) rescue KeyError => e raise BadProofError.new("missing proof with hash #{e.message}") end result end end include Nodes attr_accessor :root_hash def initialize(db: {}, root_hash: BLANK_NODE_HASH, prune: false) @db = db @root_hash = root_hash @prune = prune end def put(key, value, node: root_node) trie_key = Nibbles.bytes_to_nibbles(key) new_node = put_without_update_root_node(trie_key, value, node: node) update_root_node(new_node) new_node end def []=(key, value) put(key, value) end def get(trie_key, node: root_node) trie_key = Nibbles.bytes_to_nibbles(trie_key) if trie_key.is_a?(String) case node when NullNode NullNode::NULL.to_s when Leaf trie_key == node.extract_key ? node.value : NullNode::NULL.to_s when Extension if trie_key[0...node.extract_key.size] == node.extract_key sub_node = get_node(node.node_hash) get(trie_key[node.extract_key.size..-1], node: sub_node) else NullNode::NULL.to_s end when Branch if trie_key.empty? node.value else sub_node = get_node(node[trie_key[0]]) get(trie_key[1..-1], node: sub_node) end else raise "unknown node type #{node}" end end def fetch(trie_key) result = get(trie_key) raise KeyError.new("key not found: #{trie_key}") if result.nil? result end def [](key) get(key) rescue KeyError nil end def exists?(key) get(key) != NullNode::NULL end alias include? exists? def delete(key, node: root_node) trie_key = Nibbles.bytes_to_nibbles(key) new_node = delete_without_update_root_node(trie_key, node: node) update_root_node(new_node) new_node end def get_node(node_hash) if node_hash == BLANK_NODE_HASH return NullNode::NULL elsif node_hash == NullNode::NULL return NullNode::NULL end if node_hash.size < 32 encoded_node = node_hash else encoded_node = @db.fetch(node_hash) end Node.decode(encoded_node) end def root_node get_node(@root_hash) end def root_node=(value) update_root_node(value) end def persist_node(node) key, value = node_to_db_mapping(node) if value @db[key] = value end key end private def put_without_update_root_node(trie_key, value, node:) prune_node(node) case node when NullNode key = Node.compute_leaf_key(trie_key) Leaf.new(key, value) when Leaf, Extension current_key = node.extract_key common_prefix, current_key_remainder, trie_key_remainder = Node.consume_common_prefix( current_key, trie_key, ) if current_key_remainder.empty? && trie_key_remainder.empty? # put value to current leaf or extension if node.is_a?(Leaf) return Leaf.new(node.key, value) else sub_node = get_node(node.node_hash) new_node = put_without_update_root_node(trie_key_remainder, value, node: sub_node) end elsif current_key_remainder.empty? # put value to new sub_node if node.is_a?(Extension) sub_node = get_node(node.node_hash) new_node = put_without_update_root_node(trie_key_remainder, value, node: sub_node) else subnode_position = trie_key_remainder[0] subnode_key = Node.compute_leaf_key(trie_key_remainder[1..-1]) sub_node = Leaf.new(subnode_key, value) # new leaf new_node = Branch.new_with_value(value: node.value) new_node[subnode_position] = persist_node(sub_node) new_node end else new_node = Branch.new if current_key_remainder.size == 1 && node.is_a?(Extension) new_node[current_key_remainder[0]] = node.node_hash else sub_node = if node.is_a?(Extension) key = Node.compute_extension_key(current_key_remainder[1..-1]) Extension.new(key, node.node_hash) else key = Node.compute_leaf_key(current_key_remainder[1..-1]) Leaf.new(key, node.value) end new_node[current_key_remainder[0]] = persist_node(sub_node) end if !trie_key_remainder.empty? sub_node = Leaf.new(Node.compute_leaf_key(trie_key_remainder[1..-1]), value) new_node[trie_key_remainder[0]] = persist_node(sub_node) else new_node[-1] = value end new_node end if common_prefix.size > 0 Extension.new(Node.compute_extension_key(common_prefix), persist_node(new_node)) else new_node end when Branch if !trie_key.empty? sub_node = get_node(node[trie_key[0]]) new_node = put_without_update_root_node(trie_key[1..-1], value, node: sub_node) node[trie_key[0]] = persist_node(new_node) else node[-1] = value end node else raise "unknown node type #{node}" end end def delete_without_update_root_node(trie_key, node:) prune_node(node) case node when NullNode NullNode::NULL when Leaf, Extension delete_kv_node(node, trie_key) when Branch delete_branch_node(node, trie_key) else raise "unknown node type #{node}" end end def update_root_node(root_node) if @prune old_root_hash = @root_hash if old_root_hash != BLANK_NODE_HASH && @db.include?(old_root_hash) @db.delete(old_root_hash) end end if root_node.null? @root_hash = BLANK_NODE_HASH else encoded_root_node = RLP.encode_simple(root_node) new_root_hash = Utils.keccak(encoded_root_node) @db[new_root_hash] = encoded_root_node @root_hash = new_root_hash end end def node_to_db_mapping(node) return [node, nil] if node.null? encoded_node = RLP.encode_simple(node) return [node, nil] if encoded_node.size < 32 encoded_node_hash = Utils.keccak(encoded_node) [encoded_node_hash, encoded_node] end def prune_node(node) if @prune key, value = node_to_db_mapping node @db.delete(key) if value end end def normalize_branch_node(node) sub_nodes = node[0..15].map {|n| get_node(n)} return node if sub_nodes.select {|n| !n.null?}.size > 1 unless node.value.empty? return Leaf.new(compute_leaf_key([]), node.value) end sub_node, sub_node_idx = sub_nodes.each_with_index.find {|v, i| v && !v.null?} prune_node(sub_node) case sub_node when Leaf, Extension new_subnode_key = Nibbles.encode_nibbles([sub_node_idx] + Nibbles.decode_nibbles(sub_node.key)) sub_node.is_a?(Leaf) ? Leaf.new(new_subnode_key, sub_node.value) : Extension.new(new_subnode_key, sub_node.node_hash) when Branch subnode_hash = persist_node(sub_node) Extension.new(Nibbles.encode_nibbles([sub_node_idx]), subnode_hash) else raise "unknown sub_node type #{sub_node}" end end def delete_branch_node(node, trie_key) if trie_key.empty? node[-1] = NullNode::NULL return normalize_branch_node(node) end node_to_delete = get_node(node[trie_key[0]]) sub_node = delete_without_update_root_node(trie_key[1..-1], node: node_to_delete) encoded_sub_node = persist_node(sub_node) return node if encoded_sub_node == node[trie_key[0]] node[trie_key[0]] = encoded_sub_node return normalize_branch_node(node) if encoded_sub_node == NullNode::NULL node end def delete_kv_node(node, trie_key) current_key = node.extract_key # key not exists return node if trie_key[0...current_key.size] != current_key if node.is_a?(Leaf) if trie_key == current_key return NullNode::NULL else return node end end sub_node_key = trie_key[current_key.size..-1] sub_node = get_node(node.node_hash) new_sub_node = delete_without_update_root_node(sub_node_key, node: sub_node) encoded_new_sub_node = persist_node(new_sub_node) return node if encoded_new_sub_node == node.node_hash return NullNode::NULL if new_sub_node.null? if new_sub_node.is_a?(Leaf) || new_sub_node.is_a?(Extension) prune_node(new_sub_node) new_key = Nibbles.encode_nibbles(current_key + Nibbles.decode_nibbles(new_sub_node.key)) if new_sub_node.is_a?(Leaf) return Leaf.new(new_key, new_sub_node.value) else return Extension.new(new_key, new_sub_node.node_hash) end end if new_sub_node.is_a?(Branch) return Extension.new(Nibbles.encode_nibbles(current_key), encoded_new_sub_node) end raise "can't correct delete kv node" end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/version.rb
lib/ciri/version.rb
# frozen_string_literal: true module Ciri VERSION = "0.0.4" end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks.rb
lib/ciri/forks.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'forks/config' require_relative 'forks/frontier' require_relative 'forks/homestead' require_relative 'forks/tangerine_whistle' require_relative 'forks/spurious_dragon' require_relative 'forks/byzantium' require_relative 'forks/constantinople' module Ciri module Forks end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/bloom_filter.rb
lib/ciri/bloom_filter.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils' module Ciri # modified from py-evm class BloomFilter def initialize(value = 0) @value = value end def <<(value) get_bloom_bits(value).each do |v| @value |= v end end def extend(list) list.each do |value| self << value end end def |(value) BloomFilter.new(@value | value.to_i) end def include?(value) get_bloom_bits(value).all? do |bits| @value & bits != 0 end end def to_i @value end def self.from_iterable(list) b = BloomFilter.new b.extend(list) b end private def get_bloom_bits(value) value_hash = Utils.keccak(value) get_chunks_for_bloom(value_hash).map {|v| chunk_to_bloom_bits(v)} end def get_chunks_for_bloom(value) value[0..5].each_char.each_slice(2).map(&:join) end def chunk_to_bloom_bits(value) high, low = value.each_byte.to_a 1 << ((low + (high << 8)) & 2047) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/state.rb
lib/ciri/state.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'forwardable' require 'ciri/db/account_db' module Ciri class State extend Forwardable def_delegators :@account_db, :set_nonce, :increment_nonce, :set_balance, :add_balance, :find_account, :delete_account, :account_dead?, :store, :fetch, :set_account_code, :get_account_code, :account_exist? def initialize(db, state_root: nil) @db = db @account_db = DB::AccountDB.new(db, root_hash: state_root) end def snapshot [state_root, @db.dup] end def revert(snapshot) state_root, _db = snapshot @account_db = DB::AccountDB.new(@db, root_hash: state_root) end def commit(snapshot) true end def state_root @account_db.root_hash end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/serialize.rb
lib/ciri/serialize.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/types/address' require 'ciri/core_ext' using Ciri::CoreExt module Ciri module Serialize extend self def serialize(item) case item when Integer Utils.big_endian_encode(item) when Types::Address item.to_s else item end end def deserialize(type, item) if type == Integer && !item.is_a?(Integer) Utils.big_endian_decode(item.to_s) elsif type == Types::Address && !item.is_a?(Types::Address) # check if address represent in Integer item = Utils.big_endian_encode(item) if item.is_a?(Integer) Types::Address.new(item.size >= 20 ? item[-20..-1] : item.pad_zero(20)) elsif type.nil? # get serialized word serialize(item).rjust(32, "\x00".b) else item end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm.rb
lib/ciri/evm.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'forwardable' require 'ciri/forks' require 'ciri/core_ext' require 'ciri/utils' require 'ciri/types/account' require 'ciri/types/receipt' require_relative 'evm/op' require_relative 'evm/vm' require_relative 'evm/errors' require_relative 'evm/execution_context' using Ciri::CoreExt module Ciri class EVM include Utils::Logger extend Forwardable ExecutionResult = Struct.new(:status, :state_root, :logs, :gas_used, :gas_price, :exception, :output, keyword_init: true) do def logs_hash # return nil unless vm Utils.keccak(RLP.encode_simple(logs)) end end def_delegators :@state, :find_account, :account_dead?, :get_account_code, :state_root attr_reader :state, :fork_schema def initialize(state:, chain: nil, fork_schema: Ciri::Forks::Frontier::Schema.new) @state = state @fork_schema = fork_schema @chain = chain end # transition block def transition(block, check_gas_limit: true, check_gas_used: true) receipts = [] total_gas_used = 0 # execute transactions, we don't need to valid transactions, it should be done before evm(in Chain module). block.transactions.each do |transaction| result = execute_transaction(transaction, header: block.header, ignore_exception: true) total_gas_used += result.gas_used if check_gas_limit && total_gas_used > block.header.gas_limit raise InvalidTransition.new('reach block gas_limit') end if check_gas_used && total_gas_used > block.header.gas_used raise InvalidTransition.new("overflow header gas_used, total_gas_used: #{total_gas_used}, block gas_used: #{block.header.gas_used}") end receipt = fork_schema.make_receipt(execution_result: result, gas_used: total_gas_used) receipts << receipt end if check_gas_used && total_gas_used != block.header.gas_used raise InvalidTransition.new("incorrect gas_used, actual used: #{total_gas_used} header: #{block.header.gas_used}") end rewards = fork_schema.mining_rewards_of_block(block) # apply rewards rewards.each do |address, value| if value > 0 account = find_account(address) account.balance += value state.set_balance(address, account.balance) end end receipts end # execute transaction # @param t Transaction # @param header Chain::Header def execute_transaction(t, header: nil, block_info: nil, ignore_exception: false) unless state.find_account(t.sender).balance >= t.gas_price * t.gas_limit + t.value raise InvalidTransaction.new('account balance not enough') end # remove gas fee from account balance state.add_balance(t.sender, -1 * t.gas_limit * t.gas_price) intrinsic_gas = fork_schema.intrinsic_gas_of_transaction(t) if intrinsic_gas > t.gas_limit raise InvalidTransaction.new('intrinsic gas overflowed gas limit') end gas_limit = t.gas_limit - intrinsic_gas instruction = Instruction.new( origin: t.sender, price: t.gas_price, sender: t.sender, value: t.value, header: header, ) if t.contract_creation? instruction.bytes_code = t.data else instruction.bytes_code = get_account_code(t.to) instruction.address = t.to instruction.data = t.data end block_info ||= header && BlockInfo.from_header(header) context = Ciri::EVM::ExecutionContext.new( instruction: instruction, gas_limit: gas_limit, block_info: block_info, fork_schema: fork_schema ) vm = Ciri::EVM::VM.new(state: state, chain: @chain, burn_gas_on_exception: true) unless instruction.value > state.find_account(instruction.sender).balance state.increment_nonce(instruction.sender) end vm.with_context(context) do if t.contract_creation? # contract creation vm.create_contract(context: context) else vm.call_message(context: context) end raise context.exception if !ignore_exception && context.exception # refund gas sub_state_refund_gas = fork_schema.calculate_refund_gas(vm) context.refund_gas(sub_state_refund_gas) refund_gas = context.reset_refund_gas remain_gas = context.remain_gas actually_gas_used = t.gas_limit - remain_gas actually_refund_gas = [refund_gas, actually_gas_used / 2].min refund_gas_amount = (actually_refund_gas + remain_gas) * t.gas_price debug("Transaction refund #{refund_gas_amount} to #{t.sender.to_s.hex}") state.add_balance(t.sender, refund_gas_amount) # gas_used after refund gas gas_used = actually_gas_used - actually_refund_gas # miner fee fee = gas_used * t.gas_price debug("Transaction fee #{fee}") miner_account = find_account(block_info.coinbase) miner_account.balance += fee state.set_balance(block_info.coinbase, miner_account.balance) # EIP158 fork, we need to delete miner account if account become empty vm.sub_state.add_touched_account(block_info.coinbase) vm.delete_empty_accounts # destroy accounts vm.execution_context.all_suicide_accounts.each do |address| state.set_balance(address, 0) state.delete_account(address) end ExecutionResult.new(status: context.status, state_root: state_root, logs: context.all_log_series, gas_used: gas_used, gas_price: t.gas_price, exception: context.exception, output: context.output) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/errors.rb
lib/ciri/evm/errors.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri class EVM class Error < StandardError end class InvalidTransition < Error end class InvalidTransaction < Error end # VM errors class VMError < Error end class InvalidOpCodeError < VMError end class GasNotEnoughError < VMError end class StackError < VMError end class InvalidJumpError < VMError end class ReturnError < VMError end class ContractCollisionError < VMError end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/precompile_contract.rb
lib/ciri/evm/precompile_contract.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/core_ext' require 'ciri/crypto' require 'digest' using Ciri::CoreExt module Ciri class EVM module PrecompileContract class ECRecover GAS_ECRECOVER = 3000 def call(vm) vm.consume_gas(GAS_ECRECOVER) message_hash = vm.instruction.data[0...32].pad_zero(32) v = vm.instruction.data[32...64].decode_big_endian r = vm.instruction.data[64...96].decode_big_endian s = vm.instruction.data[96...128].decode_big_endian unless valid_vrs?(v, r, s) return vm.set_exception(Error.new("invalid vrs")) end raw_v = v - 27 begin signature = Ciri::Crypto::Signature.new(vrs: [raw_v, r, s]) key = Ciri::Key.ecdsa_recover(message_hash, signature) rescue StandardError => e return vm.set_exception(e) end vm.set_output(key.to_address.to_s) end def valid_vrs?(v, r, s) return false unless r < Ciri::Crypto::SECP256K1N return false unless s < Ciri::Crypto::SECP256K1N return false unless v == 28 || v == 27 true end end class SHA256 GAS_SHA256 = 60 GAS_SHA256WORD = 12 def call(vm) input_bytes = vm.instruction.data word_count = input_bytes.size.ceil_div(32) / 32 gas_fee = GAS_SHA256 + word_count * GAS_SHA256WORD vm.consume_gas(gas_fee) vm.set_output input_bytes.keccak end end class RIPEMD160 GAS_RIPEMD160 = 600 GAS_RIPEMD160WORD = 120 def call(vm) input_bytes = vm.instruction.data word_count = input_bytes.size.ceil_div(32) / 32 gas_fee = GAS_RIPEMD160 + word_count * GAS_RIPEMD160WORD vm.consume_gas(gas_fee) vm.set_output Digest::RMD160.digest(input_bytes).pad_zero(32) end end class Identity GAS_IDENTITY = 15 GAS_IDENTITYWORD = 3 def call(vm) input_bytes = vm.instruction.data word_count = input_bytes.size.ceil_div(32) / 32 gas_fee = GAS_IDENTITY + word_count * GAS_IDENTITYWORD vm.consume_gas(gas_fee) computation.output = input_bytes end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/vm.rb
lib/ciri/evm/vm.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils/logger' require 'ciri/core_ext' require 'ciri/types/log_entry' require_relative 'errors' require_relative 'execution_context' require_relative 'machine_state' require_relative 'instruction' require_relative 'sub_state' require_relative 'block_info' require_relative 'op/errors' using Ciri::CoreExt module Ciri class EVM # represent empty set, distinguished with nil EMPTY_SET = [].freeze # Here include batch constants(OP, Cost..) you can find there definition in Ethereum yellow paper. # If you can't understand some mystery formula in comments... go to read Ethereum yellow paper. # # VM: core logic of EVM # other logic of EVM (include transaction logic) in EVM module. class VM extend Forwardable # helper methods include Utils::Logger def_delegators :machine_state, :stack, :pop, :push, :pop_list, :get_stack, :memory_item, :memory_item=, :memory_store, :memory_fetch, :extend_memory def_delegators :state, :find_account, :account_dead?, :store, :fetch, :set_account_code, :get_account_code, :account_exist? # delegate methods to current execution_context def_delegators :execution_context, :instruction, :sub_state, :machine_state, :block_info, :fork_schema, :pc, :output, :exception, :set_output, :set_exception, :clear_exception, :set_pc, :status, :depth, :gas_limit, :refund_gas, :reset_refund_gas, :consume_gas, :remain_gas, :jump_to, :jump_pc def_delegators :instruction, :get_op, :get_code, :next_valid_instruction_pos, :get_data, :data, :sender, :destinations def_delegators :sub_state, :add_refund_account, :add_touched_account, :add_suicide_account attr_reader :state, :execution_context, :burn_gas_on_exception, :max_depth, :stack_size def initialize(state:, chain: nil, burn_gas_on_exception: true, max_depth: 1024, stack_size: 1024) @state = state @chain = chain @burn_gas_on_exception = burn_gas_on_exception @max_depth = max_depth @stack_size = stack_size end # run vm def run(ignore_exception: false) execute raise exception unless ignore_exception || exception.nil? end # low_level create_contract interface # CREATE_CONTRACT op is based on this method def create_contract(context: self.execution_context) caller_address = context.instruction.sender value = context.instruction.value account = find_account(caller_address) # return contract address 0 represent execution failed return 0 unless account.balance >= value || depth > max_depth snapshot = state.snapshot # generate contract_address material = RLP.encode_simple([caller_address.to_s, account.nonce - 1]) contract_address = Utils.keccak(material)[-20..-1] transact(sender: caller_address, value: value, to: contract_address) # initialize contract account contract_account = find_account(contract_address) context.instruction.address = contract_address with_context(context) do if contract_account.has_code? || contract_account.nonce > 0 err = ContractCollisionError.new("address #{contract_address.to_hex} collision") debug(err.message) set_exception(err) else execute end deposit_code_gas = fork_schema.calculate_deposit_code_gas(output) gas_is_not_enough = deposit_code_gas > remain_gas deposit_code_reach_limit = output.size > fork_schema.contract_code_size_limit # check deposit_code_gas if gas_is_not_enough || deposit_code_reach_limit contract_address = 0 if fork_schema.exception_on_deposit_code_gas_not_enough if deposit_code_reach_limit set_exception GasNotEnoughError.new("deposit_code size reach limit, code size: #{output.size}, limit size: #{fork_schema.contract_code_size_limit}") else set_exception GasNotEnoughError.new("deposit_code_gas not enough, deposit_code_gas: #{deposit_code_gas}, remain_gas: #{remain_gas}") end else set_output ''.b end elsif exception contract_address = 0 else # set contract code set_account_code(contract_address, output) if fork_schema.contract_init_nonce != 0 state.set_nonce(contract_address, fork_schema.contract_init_nonce) end # minus deposit_code_fee consume_gas deposit_code_gas end finalize_message(snapshot) [contract_address, exception] end end # low level call message interface # CALL, CALLCODE, DELEGATECALL ops is base on this method def call_message(context: self.execution_context, code_address: context.instruction.address) address = context.instruction.address value = context.instruction.value sender = context.instruction.sender # return status code 0 represent execution failed return [0, ''.b] unless value <= find_account(sender).balance && depth <= max_depth snapshot = state.snapshot transact(sender: sender, value: value, to: address) # enter new execution context with_context(context) do begin if (precompile_contract = fork_schema.find_precompile_contract(code_address)) precompile_contract.call(self) else execute end rescue GasNotEnoughError => e set_exception(e) end finalize_message(snapshot) [status, output || ''.b, exception] end end def add_log_entry(topics, log_data) sub_state.log_series << Types::LogEntry.new(address: instruction.address, topics: topics, data: log_data) end # transact value from sender to target address def transact(sender:, value:, to:) sender_account = find_account(sender) raise VMError.new("balance not enough") if sender_account.balance < value add_touched_account(sender) add_touched_account(to) state.add_balance(sender, -value) state.add_balance(to, value) end # Execute instruction with states # Ξ(σ,g,I,T) ≡ (σ′,μ′ ,A,o) def execute loop do if exception || set_exception(check_exception(@state, machine_state, instruction)) debug("check exception: #{exception}") return elsif get_op(pc) == OP::REVERT o = halt return elsif (o = halt) != EMPTY_SET return else operate next end end end def with_context(new_context) origin_context = execution_context @execution_context = new_context return_value = yield @execution_context = origin_context return_value end def extend_memory(pos, size) machine_state.extend_memory(execution_context, pos, size) end def delete_empty_accounts return unless fork_schema.clean_empty_accounts? sub_state.touched_accounts.to_set.select do |address| account_dead?(address) end.each do |address| state.delete_account(address) end end # get ancestor hash def get_ancestor_hash(current_hash, ancestor_distance) if ancestor_distance > 256 || ancestor_distance < 0 ''.b elsif ancestor_distance == 0 current_hash else parent_hash = @chain.get_header(current_hash).parent_hash get_ancestor_hash(parent_hash, ancestor_distance - 1) end end private # O(σ, μ, A, I) ≡ (σ′, μ′, A′, I) def operate w = get_op(pc) operation = fork_schema.get_operation(w) raise "can't find operation #{w}, pc #{pc}" unless operation op_cost, op_refund = fork_schema.gas_of_operation(self) debug("depth: #{depth} pc: #{pc} #{operation.name} gas: #{op_cost} stack: #{stack.size} logs: #{sub_state.log_series.size}") consume_gas op_cost refund_gas op_refund if op_refund && op_refund > 0 # call operation begin operation.call(self) rescue VMError => e set_exception(e) end set_pc case when w == OP::JUMP jump_pc when w == OP::JUMPI && jump_pc jump_pc else next_valid_instruction_pos(pc, w) end end # determinate halt or not halt def halt w = get_op(pc) if w == OP::RETURN || w == OP::REVERT operate output elsif w == OP::STOP || w == OP::SELFDESTRUCT operate nil else EMPTY_SET end end # check status def check_exception(state, ms, instruction) w = instruction.get_op(pc) case when w == OP::INVALID || fork_schema.get_operation(w).nil? InvalidOpCodeError.new "can't find op code 0x#{w.to_s(16)} pc: #{pc}" when ms.stack.size < (consume = OP.input_count(w)) StackError.new "stack not enough: stack:#{ms.stack.size} next consume: #{consume}" when remain_gas < (gas_cost = fork_schema.gas_of_operation(self).yield_self {|gas_cost, _| gas_cost}) GasNotEnoughError.new "gas not enough: gas remain:#{remain_gas} gas cost: #{gas_cost}" when w == OP::JUMP && !destinations.include?(ms.get_stack(0, Integer)) InvalidJumpError.new "invalid jump dest #{ms.get_stack(0, Integer)}" when w == OP::JUMPI && ms.get_stack(1, Integer) != 0 && !destinations.include?(ms.get_stack(0, Integer)) InvalidJumpError.new "invalid condition jump dest #{ms.get_stack(0, Integer)}" when w == OP::RETURNDATACOPY && ms.get_stack(1, Integer) + ms.get_stack(2, Integer) > ms.output.size ReturnError.new "return data copy error" when stack.size - OP.input_count(w) + OP.output_count(w) > stack_size StackError.new "stack size reach #{stack_size} limit" when depth > max_depth StackError.new "call depth reach #{max_depth} limit" else nil end end def finalize_message(snapshot) # check exception and commit/revert state if exception.is_a?(OP::RevertError) execution_context.revert_sub_state state.revert(snapshot) elsif exception if burn_gas_on_exception debug("exception: #{exception}, burn gas #{remain_gas} to zero... op code: 0x#{get_op(pc).to_s(16)}") consume_gas remain_gas end execution_context.revert_sub_state state.revert(snapshot) else delete_empty_accounts state.commit(snapshot) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/block_info.rb
lib/ciri/evm/block_info.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri class EVM # Block Info BlockInfo = Struct.new(:coinbase, :difficulty, :gas_limit, :number, :timestamp, :block_hash, :parent_hash, keyword_init: true) do def self.from_header(header) BlockInfo.new( coinbase: header.beneficiary, difficulty: header.difficulty, gas_limit: header.gas_limit, number: header.number, timestamp: header.timestamp, parent_hash: header.parent_hash, block_hash: header.get_hash, ) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/instruction.rb
lib/ciri/evm/instruction.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri class EVM # represent instruction Instruction = Struct.new(:address, :origin, :price, :data, :sender, :value, :bytes_code, :header, keyword_init: true) do def initialize(*args) super self.data ||= ''.b self.value ||= 0 self.bytes_code ||= ''.b end def get_op(pos) code_size = (bytes_code || ''.b).size return OP::STOP if pos >= code_size bytes_code[pos].ord end # get data from instruction def get_code(pos, size = 1) if size > 0 && pos < bytes_code.size && pos + size - 1 < bytes_code.size bytes_code[pos..(pos + size - 1)] else "\x00".b * size end end def get_data(pos, size) if pos < data.size && size > 0 data[pos..(pos + size - 1)].ljust(size, "\x00".b) else "\x00".b * size end end # valid destinations of bytes_code def destinations @destinations ||= destinations_by_index(bytes_code, 0) end def next_valid_instruction_pos(pos, op_code) if (OP::PUSH1..OP::PUSH32).include?(op_code) pos + op_code - OP::PUSH1 + 2 else pos + 1 end end private def destinations_by_index(bytes_code, i) destinations = [] loop do if i >= bytes_code.size break elsif bytes_code[i].bytes[0] == OP::JUMPDEST destinations << i end i = next_valid_instruction_pos(i, bytes_code[i].bytes[0]) end destinations end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/op_call.rb
lib/ciri/evm/op_call.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/types/address' module Ciri class EVM # handle EVM call operations module OPCall class Base include Types def call(vm) raise NotImplementedError end def extract_call_argument(vm) gas = vm.pop(Integer) to = vm.pop(Address) value = vm.pop(Integer) input_mem_pos, input_size = vm.pop_list(2, Integer) output_mem_pos, output_mem_size = vm.pop_list(2, Integer) # extend input output memory vm.extend_memory(input_mem_pos, input_size) vm.extend_memory(output_mem_pos, output_mem_size) data = vm.memory_fetch(input_mem_pos, input_size) [gas, to, value, data, output_mem_pos, output_mem_size] end def call_message(vm:, gas:, sender:, value:, data:, to:, code_address: to, output_mem_pos:, output_mem_size:) context = vm.execution_context child_gas_limit, child_gas_fee = context.fork_schema.gas_of_call(vm: vm, gas: gas, to: to, value: value) context.consume_gas(child_gas_fee) if context.depth + 1 > 1024 context.return_gas(child_gas_limit) vm.push 0 return end child_context = context.child_context(gas_limit: child_gas_limit) child_context.instruction.sender = sender child_context.instruction.value = value child_context.instruction.data = data child_context.instruction.address = to child_context.instruction.bytes_code = vm.state.get_account_code(code_address) status, output = vm.call_message(code_address: code_address, context: child_context) context.return_gas(child_context.remain_gas) output_size = [output_mem_size, output.size].min vm.extend_memory(output_mem_pos, output_size) vm.memory_store(output_mem_pos, output_size, output) vm.push status end end class Call < Base def call(vm) gas, to, value, data, output_mem_pos, output_mem_size = extract_call_argument(vm) call_message(vm: vm, sender: vm.instruction.address, value: value, gas: gas, to: to, data: data, code_address: to, output_mem_pos: output_mem_pos, output_mem_size: output_mem_size) end end class CallCode < Base def call(vm) gas, to, value, data, output_mem_pos, output_mem_size = extract_call_argument(vm) call_message(vm: vm, sender: vm.instruction.address, value: value, gas: gas, to: vm.instruction.address, data: data, code_address: to, output_mem_pos: output_mem_pos, output_mem_size: output_mem_size) end end class DelegateCall < Base def call(vm) gas, to, data, output_mem_pos, output_mem_size = extract_call_argument(vm) call_message(vm: vm, sender: vm.instruction.sender, value: vm.instruction.value, gas: gas, to: vm.instruction.address, data: data, code_address: to, output_mem_pos: output_mem_pos, output_mem_size: output_mem_size) end def extract_call_argument(vm) gas = vm.pop(Integer) to = vm.pop(Address) input_mem_pos, input_size = vm.pop_list(2, Integer) output_mem_pos, output_mem_size = vm.pop_list(2, Integer) # extend input output memory vm.extend_memory(input_mem_pos, input_size) vm.extend_memory(output_mem_pos, output_mem_size) data = vm.memory_fetch(input_mem_pos, input_size) [gas, to, data, output_mem_pos, output_mem_size] end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/sub_state.rb
lib/ciri/evm/sub_state.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri class EVM # sub state contained changed accounts and log_series class SubState attr_reader :suicide_accounts, :log_series, :touched_accounts, :refunds def initialize(suicide_accounts: [], log_series: [], touched_accounts: [], refunds: []) @suicide_accounts = suicide_accounts @log_series = log_series @touched_accounts = touched_accounts @refunds = refunds end EMPTY = SubState.new.freeze # support safety copy def initialize_copy(orig) super @suicide_accounts = orig.suicide_accounts.dup @log_series = orig.log_series.dup @touched_accounts = orig.touched_accounts.dup @refunds = orig.refunds.dup end def add_refund_account(address) @refunds << address end def add_touched_account(address) @touched_accounts << address end def add_suicide_account(address) @suicide_accounts << address end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/machine_state.rb
lib/ciri/evm/machine_state.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils/logger' require 'ciri/serialize' require 'ciri/evm/errors' module Ciri class EVM # represent current vm status, include stack, memory.. class MachineState include Utils::Logger attr_reader :memory, :stack def initialize(memory: ''.b, stack: []) @memory = memory @stack = stack end # fetch a list of items from stack def pop_list(count, type = nil) count.times.map {pop(type)} end # pop a item from stack def pop(type = nil) item = stack.shift item && Serialize.deserialize(type, item) end # get item from stack def get_stack(index, type = nil) item = stack[index] item && Serialize.deserialize(type, item) end # push into stack def push(item) stack.unshift(item) end # store data to memory def memory_store(start, size, data) if size > 0 && start < memory.size && start + size - 1 < memory.size memory[start..(start + size - 1)] = Serialize.serialize(data).rjust(size, "\x00".b) end end # fetch data from memory def memory_fetch(start, size) if size > 0 && start < memory.size && start + size - 1 < memory.size memory[start..(start + size - 1)] else # prevent size is too large "\x00".b * [size, memory.size].min end end def memory_item Utils.ceil_div(memory.size, 32) end # extend vm memory, used for memory_gas calculation def extend_memory(context, pos, size) if size != 0 && (new_item = Utils.ceil_div(pos + size, 32)) > memory_item debug("extend memory: from #{memory_item} -> #{new_item}") old_cost_gas = context.fork_schema.gas_of_memory memory_item new_cost_gas = context.fork_schema.gas_of_memory new_item context.consume_gas(new_cost_gas - old_cost_gas) extend_size = (new_item - memory_item) * 32 self.memory << "\x00".b * extend_size end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/op.rb
lib/ciri/evm/op.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils' require 'ciri/utils/number' require 'ciri/types/address' require_relative 'op_call' require_relative 'op/errors' module Ciri class EVM # OP module include all EVM operations module OP include Types OPERATIONS = {} Operation = Struct.new(:name, :code, :inputs, :outputs, :handler, keyword_init: true) do def call(*args) handler.call(*args) if handler end end class << self # define VM operation # this method also defined a constant under OP module def def_op(name, code, inputs, outputs, &handler) OPERATIONS[code] = Operation.new(name: name.to_s, code: code, inputs: inputs, outputs: outputs, handler: handler).freeze const_set(name, code) code end def get(code) OPERATIONS[code] end def input_count(code) get(code)&.inputs end def output_count(code) get(code)&.outputs end end MAX_INT = Utils::Number::UINT_256_CEILING # basic operations def_op :STOP, 0x00, 0, 0 def_op :ADD, 0x01, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push((a + b) % MAX_INT) end def_op :MUL, 0x02, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push((a * b) % MAX_INT) end def_op :SUB, 0x03, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push((a - b) % MAX_INT) end def_op :DIV, 0x04, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push((b.zero? ? 0 : a / b) % MAX_INT) end def_op :SDIV, 0x05, 2, 1 do |vm| a, b = vm.pop_list(2, Integer).map {|n| Utils::Number.unsigned_to_signed n} value = b.zero? ? 0 : a.abs / b.abs pos = (a > 0) ^ (b > 0) ? -1 : 1 vm.push(Utils::Number.signed_to_unsigned(value * pos) % MAX_INT) end def_op :MOD, 0x06, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push(b.zero? ? 0 : a % b) end def_op :SMOD, 0x07, 2, 1 do |vm| a, b = vm.pop_list(2, Integer).map {|n| Utils::Number.unsigned_to_signed n} value = b.zero? ? 0 : a.abs % b.abs pos = a > 0 ? 1 : -1 vm.push(Utils::Number.signed_to_unsigned(value * pos)) end def_op :ADDMOD, 0x08, 3, 1 do |vm| a, b, c = vm.pop_list(3, Integer) value = c.zero? ? 0 : (a + b) % c vm.push(value % MAX_INT) end def_op :MULMOD, 0x09, 3, 1 do |vm| a, b, c = vm.pop_list(3, Integer) vm.push(c.zero? ? 0 : (a * b) % c) end def_op :EXP, 0x0a, 2, 1 do |vm| base, x = vm.pop_list(2, Integer) vm.push(base.pow(x, MAX_INT)) end # not sure how to handle signextend, copy algorithm from py-evm def_op :SIGNEXTEND, 0x0b, 2, 1 do |vm| bits, value = vm.pop_list(2, Integer) if bits <= 31 testbit = bits * 8 + 7 sign_bit = (1 << testbit) if value & sign_bit > 0 result = value | (MAX_INT - sign_bit) else result = value & (sign_bit - 1) end else result = value end vm.push(result % MAX_INT) end def_op :LT, 0x10, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push a < b ? 1 : 0 end def_op :GT, 0x11, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push a > b ? 1 : 0 end def_op :SLT, 0x12, 2, 1 do |vm| a, b = vm.pop_list(2, Integer).map {|i| Utils::Number.unsigned_to_signed i} vm.push a < b ? 1 : 0 end def_op :SGT, 0x13, 2, 1 do |vm| a, b = vm.pop_list(2, Integer).map {|i| Utils::Number.unsigned_to_signed i} vm.push a > b ? 1 : 0 end def_op :EQ, 0x14, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push a == b ? 1 : 0 end def_op :ISZERO, 0x15, 1, 1 do |vm| a = vm.pop(Integer) vm.push a == 0 ? 1 : 0 end def_op :AND, 0x16, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push a & b end def_op :OR, 0x17, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push a | b end def_op :XOR, 0x18, 2, 1 do |vm| a, b = vm.pop_list(2, Integer) vm.push a ^ b end def_op :NOT, 0x19, 1, 1 do |vm| signed_number = Utils::Number.unsigned_to_signed vm.pop(Integer) vm.push Utils::Number.signed_to_unsigned(~signed_number) end def_op :BYTE, 0x1a, 2, 1 do |vm| pos, value = vm.pop_list(2, Integer) if pos >= 32 result = 0 else result = (value / 256.pow(31 - pos)) % 256 end vm.push result end # 20s: sha3 def_op :SHA3, 0x20, 2, 1 do |vm| pos, size = vm.pop_list(2, Integer) vm.extend_memory(pos, size) hashed = Ciri::Utils.keccak vm.memory_fetch(pos, size) vm.extend_memory(pos, size) vm.push hashed end # 30s: environment operations def_op :ADDRESS, 0x30, 0, 1 do |vm| vm.push(vm.instruction.address) end def_op :BALANCE, 0x31, 1, 1 do |vm| address = vm.pop(Address) account = vm.find_account(address) vm.push(account.balance) end def_op :ORIGIN, 0x32, 0, 1 do |vm| vm.push vm.instruction.origin end def_op :CALLER, 0x33, 0, 1 do |vm| vm.push vm.instruction.sender end def_op :CALLVALUE, 0x34, 0, 1 do |vm| vm.push vm.instruction.value end def_op :CALLDATALOAD, 0x35, 1, 1 do |vm| start = vm.pop(Integer) vm.push(vm.get_data(start, 32)) end def_op :CALLDATASIZE, 0x36, 0, 1 do |vm| vm.push vm.instruction.data.size end def_op :CALLDATACOPY, 0x37, 3, 0 do |vm| mem_pos, data_pos, size = vm.pop_list(3, Integer) data = vm.get_data(data_pos, size) vm.extend_memory(mem_pos, size) vm.memory_store(mem_pos, size, data) end def_op :CODESIZE, 0x38, 0, 1 do |vm| vm.push vm.instruction.bytes_code.size end def_op :CODECOPY, 0x39, 3, 0 do |vm| mem_pos, code_pos, size = vm.pop_list(3, Integer) data = vm.get_code(code_pos, size) vm.extend_memory(mem_pos, size) vm.memory_store(mem_pos, size, data) end def_op :GASPRICE, 0x3a, 0, 1 do |vm| vm.push vm.instruction.price end def_op :EXTCODESIZE, 0x3b, 0, 1 do |vm| address = vm.pop(Address) code_size = vm.get_account_code(address).size vm.push code_size end def_op :EXTCODECOPY, 0x3c, 4, 0 do |vm| address = vm.pop(Address) mem_pos, data_pos, size = vm.pop_list(3, Integer) code = vm.get_account_code(address) data_end_pos = data_pos + size - 1 data = if data_pos >= code.size ''.b elsif data_end_pos >= code.size code[data_pos..-1] else code[data_pos..data_end_pos] end vm.extend_memory(mem_pos, size) vm.memory_store(mem_pos, size, data) end RETURNDATASIZE = 0x3d RETURNDATACOPY = 0x3e # 40s: block information def_op :BLOCKHASH, 0x40, 1, 1 do |vm| height = vm.pop(Integer) # cause current block hash do not exists in chain # here we compute distance of parent height and ancestor height # and use parent_hash to find ancestor hash distance = vm.block_info.number - height - 1 vm.push vm.get_ancestor_hash(vm.block_info.parent_hash, distance) end def_op :COINBASE, 0x41, 0, 1 do |vm| vm.push vm.block_info.coinbase end def_op :TIMESTAMP, 0x42, 0, 1 do |vm| vm.push vm.block_info.timestamp end def_op :NUMBER, 0x43, 0, 1 do |vm| vm.push vm.block_info.number end def_op :DIFFICULTY, 0x44, 0, 1 do |vm| vm.push vm.block_info.difficulty end def_op :GASLIMIT, 0x45, 0, 1 do |vm| vm.push vm.block_info.gas_limit end # 50s: Stack, Memory, Storage and Flow Operations def_op :POP, 0x50, 1, 0 do |vm| vm.pop end def_op :MLOAD, 0x51, 1, 1 do |vm| index = vm.pop(Integer) vm.extend_memory(index, 32) vm.push vm.memory_fetch(index, 32) end def_op :MSTORE, 0x52, 2, 0 do |vm| index = vm.pop(Integer) data = vm.pop vm.extend_memory(index, 32) vm.memory_store(index, 32, data) end def_op :MSTORE8, 0x53, 2, 0 do |vm| index = vm.pop(Integer) data = vm.pop(Integer) vm.extend_memory(index, 8) vm.memory_store(index, 1, data % 256) end def_op :SLOAD, 0x54, 1, 1 do |vm| key = vm.pop(Integer) vm.push vm.fetch(vm.instruction.address, key) end def_op :SSTORE, 0x55, 2, 0 do |vm| key = vm.pop(Integer) value = vm.pop(Integer) vm.store(vm.instruction.address, key, value) end def_op :JUMP, 0x56, 1, 0 do |vm| pc = vm.pop(Integer) vm.jump_to(pc) end def_op :JUMPI, 0x57, 2, 0 do |vm| dest, cond = vm.pop_list(2, Integer) # if cond is non zero jump to dest, else just goto next pc if cond != 0 vm.jump_to(dest) else # clear jump_to vm.jump_to(nil) end end def_op :PC, 0x58, 0, 1 do |vm| vm.push vm.pc end def_op :MSIZE, 0x59, 0, 1 do |vm| vm.push 32 * vm.memory_item end def_op :GAS, 0x5a, 0, 1 do |vm| vm.push vm.remain_gas end def_op :JUMPDEST, 0x5b, 0, 0 # 60s & 70s: Push Operations # PUSH1 - PUSH32 (1..32).each do |i| name = "PUSH#{i}" def_op name, 0x60 + i - 1, 0, 1, &(proc do |byte_size| proc do |vm| vm.push vm.get_code(vm.pc + 1, byte_size) end end.call(i)) end # 80s: Duplication Operations # DUP1 - DUP16 (1..16).each do |i| name = "DUP#{i}" def_op name, 0x80 + i - 1, i, i + 1, &(proc do |i| proc do |vm| vm.push vm.stack[i - 1].dup end end.call(i)) end # 90s: Exchange Operations # SWAP1 - SWAP16 (1..16).each do |i| name = "SWAP#{i}" def_op name, 0x90 + i - 1, i + 1, i + 1, &(proc do |i| proc do |vm| vm.stack[0], vm.stack[i] = vm.stack[i], vm.stack[0] end end.call(i)) end # a0s: Logging Operations # LOG0 - LOG4 (0..4).each do |i| name = "LOG#{i}" def_op name, 0xa0 + i, i + 2, 0, &(proc do |i| proc do |vm| pos, size = vm.pop_list(2, Integer) vm.extend_memory(pos, size) log_data = vm.memory_fetch(pos, size) topics = vm.pop_list(i, Integer) vm.add_log_entry(topics, log_data) end end.call(i)) end # f0s: System operations def_op :CREATE, 0xf0, 3, 1 do |vm| value = vm.pop(Integer) mem_pos, size = vm.pop_list(2, Integer) vm.extend_memory(mem_pos, size) # have not enough money if vm.find_account(vm.instruction.address).balance < value vm.push(0) else init = vm.memory_fetch(mem_pos, size) create_gas = vm.remain_gas vm.consume_gas(create_gas) child_context = vm.execution_context.child_context(gas_limit: create_gas) child_context.instruction.value = value child_context.instruction.bytes_code = init contract_address, _ = vm.create_contract(context: child_context) vm.execution_context.return_gas(child_context.remain_gas) vm.push contract_address end end def_op :CALL, 0xf1, 7, 1 do |vm| OPCall::Call.new.call(vm) end def_op :CALLCODE, 0xf2, 7, 1 do |vm| OPCall::CallCode.new.call(vm) end def_op :RETURN, 0xf3, 2, 0 do |vm| index, size = vm.pop_list(2, Integer) vm.extend_memory(index, size) vm.set_output vm.memory_fetch(index, size) end def_op :DELEGATECALL, 0xf4, 6, 1 do |vm| OPCall::DelegateCall.new.call(vm) end STATICCALL = 0xfa def_op :REVERT, 0xfd, 2, 0 do |vm| index, size = vm.pop_list(2, Integer) vm.extend_memory(index, size) output = vm.memory_fetch(index, size) vm.set_exception RevertError.new vm.set_output output end def_op :INVALID, 0xfe, 0, 0 do |vm| raise 'should not invoke INVALID' end def_op :SELFDESTRUCT, 0xff, 1, 0 do |vm| refund_address = vm.pop(Address) contract_account = vm.find_account vm.instruction.address vm.state.add_balance(refund_address, contract_account.balance) vm.state.set_balance(vm.instruction.address, 0) # register changed accounts vm.add_refund_account(refund_address) vm.add_suicide_account(vm.instruction.address) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/execution_context.rb
lib/ciri/evm/execution_context.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils/logger' require 'ciri/evm/errors' module Ciri class EVM class ExecutionContext include Utils::Logger attr_accessor :instruction, :depth, :pc, :exception, :gas_limit, :block_info, :sub_state, :fork_schema attr_reader :children, :remain_gas, :machine_state def initialize(instruction:, depth: 0, gas_limit:, remain_gas: gas_limit, fork_schema:, pc: 0, block_info:, sub_state: SubState::EMPTY.dup, machine_state: MachineState.new) raise ArgumentError.new("remain_gas must more than 0") if remain_gas < 0 raise ArgumentError.new("gas_limit must more than 0") if gas_limit < 0 @instruction = instruction @depth = depth @gas_limit = gas_limit @block_info = block_info @sub_state = sub_state @remain_gas = remain_gas @fork_schema = fork_schema @pc = pc @children = [] @refund_gas = 0 @machine_state = machine_state end # jump to pc # only valid if current op code is allowed to modify pc def jump_to(pc) # allow pc = nil to clear exist @jump_to unless pc.nil? || instruction.destinations.include?(pc) raise EVM::InvalidJumpError.new("invalid jump in runtime, pc: #{pc}") end @jump_to = pc end def jump_pc @jump_to end def set_exception(e) @exception ||= e end def clear_exception @exception = nil end def set_output(output) @output ||= output end def output @output || ''.b end def set_pc(pc) @pc = pc end def revert_sub_state @sub_state = SubState::EMPTY end def status exception.nil? ? 1 : 0 end def child_context(instruction: self.instruction.dup, depth: self.depth + 1, pc: 0, gas_limit:) child = ExecutionContext.new( instruction: instruction, depth: depth, pc: pc, gas_limit: gas_limit, block_info: block_info, sub_state: SubState.new, remain_gas: gas_limit, fork_schema: fork_schema, ) children << child child end def consume_gas(gas) raise GasNotEnoughError.new("can't consume gas to negative, remain_gas: #{remain_gas}, consumed: #{gas}") if gas > remain_gas debug "consume #{gas} gas, from #{@remain_gas} -> #{@remain_gas - gas}" @remain_gas -= gas end def return_gas(gas) raise ArgumentError.new("can't return negative gas, gas: #{gas}") if gas < 0 debug "return #{gas} gas, from #{@remain_gas} -> #{@remain_gas + gas}" @remain_gas += gas end def reset_refund_gas refund_gas = @refund_gas @refund_gas = 0 refund_gas end def refund_gas(gas) raise ArgumentError.new("gas can't be negative: #{gas}") if gas < 0 debug "refund #{gas} gas" @refund_gas += gas end # used gas of context def used_gas @gas_limit - @remain_gas end def all_log_series sub_state.log_series + children.map {|c| c.all_log_series}.flatten end def all_suicide_accounts (sub_state.suicide_accounts + children.map {|c| c.all_suicide_accounts}.flatten).uniq(&:to_s) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/evm/op/errors.rb
lib/ciri/evm/op/errors.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri class EVM module OP class OPError < StandardError end class RevertError < OPError def set_output(output) @output = output end def output @output || ''.b end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/byzantium.rb
lib/ciri/forks/byzantium.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'base' require_relative 'spurious_dragon' require_relative 'byzantium/opcodes' require 'ciri/types/receipt' require 'ciri/utils' require 'ciri/rlp' module Ciri module Forks # https://github.com/ethereum/EIPs/blob/181867ae830df5419eb9982d2a24797b2dcad28f/EIPS/eip-609.md module Byzantium class Schema < Forks::SpuriousDragon::Schema BLOCK_REWARD = 3 * 10.pow(18) # 3 ether TRANSACTION_STATUS_FAILURE = ''.b TRANSACTION_STATUS_SUCCESS = "\x01".b BLANK_OMMERS_HASH = Utils.keccak(RLP.encode([])).freeze def calculate_difficulty(header, parent_header) # https://github.com/ethereum/EIPs/blob/984cf5de90bbf5fbe7e49be227b0c2f9567e661e/EIPS/eip-100.md y = parent_header.ommers_hash == BLANK_OMMERS_HASH ? 1 : 2 difficulty_time_factor = [y - (header.timestamp - parent_header.timestamp) / 9, -99].max x = parent_header.difficulty / 2048 # difficulty bomb height = [(header.number - 3000000), 0].max height_factor = 2 ** (height / 100000 - 2) difficulty = (parent_header.difficulty + x * difficulty_time_factor + height_factor).to_i [header.difficulty, difficulty].max end def get_operation(op) OPCODES[op] end def mining_rewards_of_block(block) rewards = Hash.new(0) # reward miner rewards[block.header.beneficiary] += ((1 + block.ommers.count.to_f / 32) * BLOCK_REWARD).to_i # reward ommer(uncle) block miners block.ommers.each do |ommer| rewards[ommer.beneficiary] += ((1 + (ommer.number - block.header.number).to_f / 8) * BLOCK_REWARD).to_i end rewards end # https://github.com/ethereum/EIPs/blob/181867ae830df5419eb9982d2a24797b2dcad28f/EIPS/eip-658.md def make_receipt(execution_result:, gas_used:) status = execution_result.status == 1 ? TRANSACTION_STATUS_SUCCESS : TRANSACTION_STATUS_FAILURE Types::Receipt.new(state_root: status, gas_used: gas_used, logs: execution_result.logs) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/homestead.rb
lib/ciri/forks/homestead.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'base' require_relative 'frontier' require_relative 'homestead/transaction' require_relative 'homestead/opcodes' module Ciri module Forks # Homestead fork # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-606.md module Homestead class Schema < Forks::Frontier::Schema include Forks::Frontier def initialize(support_dao_fork:) @support_dao_fork = support_dao_fork super() end def intrinsic_gas_of_transaction(t) gas = (t.data.each_byte || '').reduce(0) {|sum, i| sum + (i.zero? ? Cost::G_TXDATAZERO : Cost::G_TXDATANONZERO)} gas + (t.to.empty? ? Cost::G_TXCREATE : 0) + Cost::G_TRANSACTION end def calculate_difficulty(header, parent_header) # https://github.com/ethereum/EIPs/blob/984cf5de90bbf5fbe7e49be227b0c2f9567e661e/EIPS/eip-2.md difficulty_time_factor = [1 - (header.timestamp - parent_header.timestamp) / 10, -99].max x = parent_header.difficulty / 2048 # difficulty bomb height = header.number height_factor = 2 ** (height / 100000 - 2) difficulty = (parent_header.difficulty + x * difficulty_time_factor + height_factor).to_i [header.difficulty, difficulty].max end def transaction_class Transaction end def get_operation(op) OPCODES[op] end def exception_on_deposit_code_gas_not_enough true end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/frontier.rb
lib/ciri/forks/frontier.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'base' require_relative 'frontier/cost' require_relative 'frontier/transaction' require_relative 'frontier/opcodes' require 'ciri/types/receipt' require 'ciri/core_ext' require 'ciri/evm/precompile_contract' require 'forwardable' using Ciri::CoreExt module Ciri module Forks module Frontier class Schema < Base extend Forwardable BLOCK_REWARD = 5 * 10.pow(18) # 5 ether def initialize @cost = Cost.new end def_delegators :@cost, :gas_of_operation, :gas_of_memory, :gas_of_call, :intrinsic_gas_of_transaction def calculate_deposit_code_gas(code_bytes) Cost::G_CODEDEPOSIT * (code_bytes || ''.b).size end def calculate_refund_gas(vm) vm.execution_context.all_suicide_accounts.size * Cost::R_SELFDESTRUCT end def mining_rewards_of_block(block) rewards = Hash.new(0) # reward miner rewards[block.header.beneficiary] += ((1 + block.ommers.count.to_f / 32) * BLOCK_REWARD).to_i # reward ommer(uncle) block miners block.ommers.each do |ommer| rewards[ommer.beneficiary] += ((1 + (ommer.number - block.header.number).to_f / 8) * BLOCK_REWARD).to_i end rewards end def calculate_difficulty(header, parent_header) difficulty_time_factor = (header.timestamp - parent_header.timestamp) < 13 ? 1 : -1 x = parent_header.difficulty / 2048 # difficulty bomb height = header.number height_factor = 2 ** (height / 100000 - 2) difficulty = (parent_header.difficulty + x * difficulty_time_factor + height_factor).to_i [header.difficulty, difficulty].max end PRECOMPILE_CONTRACTS = { "\x01".pad_zero(20).b => EVM::PrecompileContract::ECRecover.new, "\x02".pad_zero(20).b => EVM::PrecompileContract::SHA256.new, "\x03".pad_zero(20).b => EVM::PrecompileContract::RIPEMD160.new, "\x04".pad_zero(20).b => EVM::PrecompileContract::Identity.new, }.freeze # EVM op code and contract def find_precompile_contract(address) PRECOMPILE_CONTRACTS[address.to_s] end def transaction_class Transaction end def get_operation(op) OPCODES[op] end def exception_on_deposit_code_gas_not_enough false end def contract_code_size_limit Float::INFINITY end def contract_init_nonce 0 end def clean_empty_accounts? false end def make_receipt(execution_result:, gas_used:) Types::Receipt.new(state_root: execution_result.state_root, gas_used: gas_used, logs: execution_result.logs) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/base.rb
lib/ciri/forks/base.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri module Forks class Base # gas methods def gas_of_operation(vm) raise NotImplementedError end def gas_of_memory(word_count) raise NotImplementedError end def gas_of_call(vm:, gas:, to:, value:) raise NotImplementedError end def intrinsic_gas_of_transaction(transaction) raise NotImplementedError end def calculate_deposit_code_gas(code_bytes) raise NotImplementedError end def mining_rewards_of_block(block) raise NotImplementedError end def calculate_refund_gas(vm) raise NotImplementedError end # chain difficulty method def difficulty_time_factor(header, parent_header) raise NotImplementedError end def difficulty_virtual_height(height) raise NotImplementedError end # EVM op code and contract def find_precompile_contract(address) raise NotImplementedError end def transaction_class raise NotImplementedError end def get_operation(op_code) raise NotImplementedError end def exception_on_deposit_code_gas_not_enough raise NotImplementedError end def contract_code_size_limit raise NotImplementedError end def contract_init_nonce raise NotImplementedError end def clean_empty_accounts? raise NotImplementedError end def make_receipt(execution_result:, gas_used:) raise NotImplementedError end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/constantinople.rb
lib/ciri/forks/constantinople.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'base' require_relative 'byzantium' module Ciri module Forks module Constantinople class Schema < Forks::Byzantium::Schema end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/config.rb
lib/ciri/forks/config.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri module Forks class Config # @schema_rule [[0, Frontier], [100, Homestead]] def initialize(schema_rules) @schema_rules = schema_rules end def choose_fork(number) @schema_rules.reverse_each.find do |start_number, _schema| number >= start_number end[1] end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/tangerine_whistle.rb
lib/ciri/forks/tangerine_whistle.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'base' require_relative 'homestead' require_relative 'tangerine_whistle/cost' module Ciri module Forks # Tangerine Whistle fork # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-608.md module TangerineWhistle class Schema < Forks::Homestead::Schema def initialize super(support_dao_fork: false) @cost = Cost.new end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/spurious_dragon.rb
lib/ciri/forks/spurious_dragon.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'base' require_relative 'tangerine_whistle' require_relative 'spurious_dragon/transaction' require_relative 'spurious_dragon/cost' module Ciri module Forks # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-607.md module SpuriousDragon class Schema < Forks::TangerineWhistle::Schema CONTRACT_CODE_SIZE_LIMIT = 2 ** 14 + 2 ** 13 def initialize super @cost = Cost.new end def transaction_class Transaction end def contract_code_size_limit CONTRACT_CODE_SIZE_LIMIT end def contract_init_nonce 1 end def clean_empty_accounts? true end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/homestead/opcodes.rb
lib/ciri/forks/homestead/opcodes.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/evm/op' require 'ciri/forks/frontier/opcodes' module Ciri module Forks module Homestead include Ciri::EVM::OP UPDATE_OPCODES = [ DELEGATECALL, ].map do |op| [op, Ciri::EVM::OP.get(op)] end.to_h.freeze OPCODES = Frontier::OPCODES.merge(UPDATE_OPCODES).freeze end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/homestead/transaction.rb
lib/ciri/forks/homestead/transaction.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/forks/frontier/transaction' module Ciri module Forks module Homestead class Transaction < Frontier::Transaction def validate! super raise InvalidError.new('signature s is low') unless signature.low_s? end def validate_intrinsic_gas! begin fork_schema = Schema.new(support_dao_fork: false) intrinsic_gas = fork_schema.intrinsic_gas_of_transaction(self) rescue StandardError raise InvalidError.new 'intrinsic gas calculation error' end raise InvalidError.new 'intrinsic gas not enough' unless intrinsic_gas <= gas_limit end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/spurious_dragon/cost.rb
lib/ciri/forks/spurious_dragon/cost.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/evm/op' require 'ciri/forks/tangerine_whistle/cost' module Ciri module Forks module SpuriousDragon class Cost < TangerineWhistle::Cost include Ciri::EVM::OP # fee schedule, start with G G_EXP = 10 G_EXPBYTE = 50 R_SELFDESTRUCT = 24000 G_SELFDESTRUCT = 5000 G_CALL = 700 G_NEWACCOUNT = 25000 G_CALLSTIPEND = 2300 G_CALLVALUE = 9000 # C(σ,μ,I) # calculate cost of current operation def gas_of_operation(vm) ms = vm.machine_state instruction = vm.instruction w = instruction.get_op(vm.pc) if w == CALL || w == CALLCODE || w == DELEGATECALL G_CALL elsif w == SELFDESTRUCT cost_of_self_destruct(vm) elsif w == EXP && ms.get_stack(1, Integer) == 0 G_EXP elsif w == EXP && (x = ms.get_stack(1, Integer)) > 0 G_EXP + G_EXPBYTE * Utils.ceil_div(x.bit_length, 8) else super end end def gas_of_call(vm:, gas:, to:, value:) account_is_dead = vm.account_dead?(to) value_exists = value > 0 transfer_gas_fee = value_exists ? G_CALLVALUE : 0 create_gas_fee = account_is_dead && value_exists ? G_NEWACCOUNT : 0 extra_gas = transfer_gas_fee + create_gas_fee gas = [gas, max_child_gas_eip150(vm.remain_gas - extra_gas)].min total_fee = gas + extra_gas child_gas_limit = gas + (value_exists ? G_CALLSTIPEND : 0) [child_gas_limit, total_fee] end private def max_child_gas_eip150(gas) gas - (gas / 64) end def cost_of_self_destruct(vm) refund_address = vm.get_stack(0, Address) if vm.account_exist?(refund_address) G_SELFDESTRUCT else G_SELFDESTRUCT + G_NEWACCOUNT end end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/spurious_dragon/transaction.rb
lib/ciri/forks/spurious_dragon/transaction.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/forks/homestead/transaction' module Ciri module Forks module SpuriousDragon class Transaction < Homestead::Transaction def v_min if eip_155_signed_transaction? 35 + (2 * chain_id) else 27 end end def v_max if eip_155_signed_transaction? 36 + (2 * chain_id) else 28 end end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/frontier/cost.rb
lib/ciri/forks/frontier/cost.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/evm/op' module Ciri module Forks module Frontier class Cost include Ciri::EVM::OP # fee schedule, start with G G_ZERO = 0 G_BASE = 2 G_VERYLOW = 3 G_LOW = 5 G_MID = 8 G_HIGH = 10 G_EXTCODE = 20 G_BALANCE = 20 G_SLOAD = 50 G_JUMPDEST = 1 G_SSET = 20000 G_RESET = 5000 R_SCLEAR = 15000 R_SELFDESTRUCT = 24000 G_SELFDESTRUCT = 0 G_CREATE = 32000 G_CODEDEPOSIT = 200 G_CALL = 40 G_CALLVALUE = 9000 G_CALLSTIPEND = 2300 G_NEWACCOUNT = 25000 G_EXP = 10 G_EXPBYTE = 10 G_MEMORY = 3 G_TXCREATE = 32000 G_TXDATAZERO = 4 G_TXDATANONZERO = 68 G_TRANSACTION = 21000 G_LOG = 375 G_LOGDATA = 8 G_TOPIC = 375 G_SHA3 = 30 G_SHA3WORD = 6 G_COPY = 3 G_BLOCKHASH = 20 G_QUADDIVISOR = 100 # operation code by group, for later calculation W_ZERO = [STOP, RETURN, REVERT] W_BASE = [ADDRESS, ORIGIN, CALLER, CALLVALUE, CALLDATASIZE, CODESIZE, GASPRICE, COINBASE, TIMESTAMP, NUMBER, DIFFICULTY, GASLIMIT, RETURNDATASIZE, POP, PC, MSIZE, GAS] W_VERYLOW = [ADD, SUB, NOT, LT, GT, SLT, SGT, EQ, ISZERO, AND, OR, XOR, BYTE, CALLDATALOAD, MLOAD, MSTORE, MSTORE8, *(1..32).map {|i| EVM::OP.get(PUSH1 + i - 1).code}, # push1 - push32 *(1..16).map {|i| EVM::OP.get(DUP1 + i - 1).code}, # dup1 - dup16 *(1..16).map {|i| EVM::OP.get(SWAP1 + i - 1).code}] # swap1 - swap16 W_LOW = [MUL, DIV, SDIV, MOD, SMOD, SIGNEXTEND] W_MID = [ADDMOD, MULMOD, JUMP] W_HIGH = [JUMPI] W_EXTCODE = [EXTCODESIZE] # C(σ,μ,I) # calculate cost of current operation def gas_of_operation(vm) ms = vm.machine_state instruction = vm.instruction w = instruction.get_op(vm.pc) if w == SSTORE cost_of_sstore(vm) elsif w == EXP && ms.get_stack(1, Integer) == 0 G_EXP elsif w == EXP && (x = ms.get_stack(1, Integer)) > 0 G_EXP + G_EXPBYTE * Utils.ceil_div(x.bit_length, 8) elsif w == CALLDATACOPY || w == CODECOPY || w == RETURNDATACOPY G_VERYLOW + G_COPY * Utils.ceil_div(ms.get_stack(2, Integer), 32) elsif w == EXTCODECOPY G_EXTCODE + G_COPY * Utils.ceil_div(ms.get_stack(3, Integer), 32) elsif (LOG0..LOG4).include? w G_LOG + G_LOGDATA * ms.get_stack(1, Integer) + (w - LOG0) * G_TOPIC elsif w == CALL || w == CALLCODE || w == DELEGATECALL G_CALL elsif w == SELFDESTRUCT cost_of_self_destruct(vm) elsif w == CREATE G_CREATE elsif w == SHA3 G_SHA3 + G_SHA3WORD * Utils.ceil_div(ms.get_stack(1, Integer), 32) elsif w == JUMPDEST G_JUMPDEST elsif w == SLOAD G_SLOAD elsif W_ZERO.include? w G_ZERO elsif W_BASE.include? w G_BASE elsif W_VERYLOW.include? w G_VERYLOW elsif W_LOW.include? w G_LOW elsif W_MID.include? w G_MID elsif W_HIGH.include? w G_HIGH elsif W_EXTCODE.include? w G_EXTCODE elsif w == BALANCE G_BALANCE elsif w == BLOCKHASH G_BLOCKHASH else raise "can't compute cost for unknown op #{w}" end end def gas_of_memory(i) G_MEMORY * i + (i ** 2) / 512 end def intrinsic_gas_of_transaction(t) gas = (t.data.each_byte || '').reduce(0) {|sum, i| sum + (i.zero? ? G_TXDATAZERO : G_TXDATANONZERO)} # gas + (t.to.empty? ? G_TXCREATE : 0) + G_TRANSACTION gas + G_TRANSACTION end def gas_of_call(vm:, gas:, to:, value:) # TODO handle gas calculation for all categories calls account_exists = vm.account_exist?(to) transfer_gas_fee = value > 0 ? G_CALLVALUE : 0 create_gas_fee = !account_exists ? G_NEWACCOUNT : 0 extra_gas = transfer_gas_fee + create_gas_fee total_fee = gas + extra_gas child_gas_limit = gas + (value > 0 ? G_CALLSTIPEND : 0) [child_gas_limit, total_fee] end private def cost_of_self_destruct(vm) G_SELFDESTRUCT end def cost_of_sstore(vm) ms = vm.machine_state instruction = vm.instruction key = ms.get_stack(0, Integer) value = ms.get_stack(1, Integer) current_is_empty = vm.fetch(instruction.address, key).zero? value_is_empty = value.nil? || value.zero? gas_cost = if current_is_empty && !value_is_empty G_SSET else G_RESET end gas_refund = if !current_is_empty && value_is_empty R_SCLEAR else 0 end [gas_cost, gas_refund] end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/frontier/opcodes.rb
lib/ciri/forks/frontier/opcodes.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/evm/op' module Ciri module Forks module Frontier include Ciri::EVM::OP OPCODES = [ STOP, ADD, MUL, SUB, DIV, SDIV, MOD, SMOD, ADDMOD, MULMOD, EXP, SIGNEXTEND, LT, GT, SLT, SGT, EQ, ISZERO, AND, OR, XOR, NOT, BYTE, SHA3, ADDRESS, BALANCE, ORIGIN, CALLER, CALLVALUE, CALLDATALOAD, CALLDATASIZE, CALLDATACOPY, CODESIZE, CODECOPY, GASPRICE, EXTCODESIZE, EXTCODECOPY, BLOCKHASH, COINBASE, TIMESTAMP, NUMBER, DIFFICULTY, GASLIMIT, POP, MLOAD, MSTORE, MSTORE8, SLOAD, SSTORE, JUMP, JUMPI, PC, MSIZE, GAS, JUMPDEST, *(PUSH1..PUSH32), *(DUP1..DUP16), *(SWAP1..SWAP16), *(LOG0..LOG4), CREATE, CALL, CALLCODE, RETURN, INVALID, SELFDESTRUCT, ].map do |op| [op, Ciri::EVM::OP.get(op)] end.to_h.freeze end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/frontier/transaction.rb
lib/ciri/forks/frontier/transaction.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/pow_chain/transaction' module Ciri module Forks module Frontier class Transaction < POWChain::Transaction def validate! validate_sender! raise InvalidError.new('signature rvs error') unless signature.valid? raise InvalidError.new('gas_price overflow') unless UInt256.valid?(gas_price) raise InvalidError.new('nonce overflow') unless UInt256.valid?(nonce) raise InvalidError.new('gas_limit overflow') unless UInt256.valid?(gas_limit) raise InvalidError.new('value overflow') unless UInt256.valid?(value) unless v >= v_min && v <= v_max raise InvalidError.new("v can be only 27 or 28 in frontier schema, found: #{v}") end validate_intrinsic_gas! end def v_min 27 end def v_max 28 end def validate_intrinsic_gas! begin fork_schema = Schema.new intrinsic_gas = fork_schema.intrinsic_gas_of_transaction(self) rescue StandardError raise InvalidError.new 'intrinsic gas calculation error' end raise InvalidError.new 'intrinsic gas not enough' unless intrinsic_gas <= gas_limit end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/tangerine_whistle/cost.rb
lib/ciri/forks/tangerine_whistle/cost.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/evm/op' require 'ciri/forks/frontier/cost' module Ciri module Forks module TangerineWhistle class Cost < Frontier::Cost include Ciri::EVM::OP # fee schedule, start with G G_EXTCODE = 700 G_BALANCE = 400 G_SLOAD = 200 R_SELFDESTRUCT = 24000 G_SELFDESTRUCT = 5000 G_CALL = 700 G_NEWACCOUNT = 25000 G_COPY = 3 G_CALLSTIPEND = 2300 G_CALLVALUE = 9000 W_EXTCODE = [EXTCODESIZE] # C(σ,μ,I) # calculate cost of current operation def gas_of_operation(vm) ms = vm.machine_state instruction = vm.instruction w = instruction.get_op(vm.pc) if w == EXTCODECOPY G_EXTCODE + G_COPY * Utils.ceil_div(ms.get_stack(3, Integer), 32) elsif w == CALL || w == CALLCODE || w == DELEGATECALL G_CALL elsif w == SELFDESTRUCT cost_of_self_destruct(vm) elsif w == SLOAD G_SLOAD elsif W_EXTCODE.include? w G_EXTCODE elsif w == BALANCE G_BALANCE else super end end def gas_of_call(vm:, gas:, to:, value:) account_exists = vm.account_exist?(to) transfer_gas_fee = value > 0 ? G_CALLVALUE : 0 create_gas_fee = !account_exists ? G_NEWACCOUNT : 0 extra_gas = transfer_gas_fee + create_gas_fee gas = [gas, max_child_gas_eip150(vm.remain_gas - extra_gas)].min total_fee = gas + extra_gas child_gas_limit = gas + (value > 0 ? G_CALLSTIPEND : 0) [child_gas_limit, total_fee] end private def max_child_gas_eip150(gas) gas - (gas / 64) end def cost_of_self_destruct(vm) balance_is_zero = vm.find_account(vm.instruction.address).balance == 0 refund_address = vm.get_stack(0, Address) if vm.account_exist?(refund_address) || balance_is_zero G_SELFDESTRUCT else G_SELFDESTRUCT + G_NEWACCOUNT end end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/forks/byzantium/opcodes.rb
lib/ciri/forks/byzantium/opcodes.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/evm/op' require 'ciri/forks/homestead/opcodes' module Ciri module Forks module Byzantium include Ciri::EVM::OP UPDATE_OPCODES = [ REVERT, ].map do |op| [op, Ciri::EVM::OP.get(op)] end.to_h.freeze OPCODES = Homestead::OPCODES.merge(UPDATE_OPCODES).freeze end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/trie/nodes.rb
lib/ciri/trie/nodes.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'nibbles' require 'forwardable' require 'ciri/utils' module Ciri class Trie module Nodes class InvalidNode < StandardError end class Node def null? false end def branch? false end class << self def decode(hash_or_encoded) if hash_or_encoded == BLANK_NODE_HASH || hash_or_encoded == Utils::BLANK_SHA3 || hash_or_encoded == ''.b return NullNode::NULL end decoded = hash_or_encoded.is_a?(String) ? RLP.decode(hash_or_encoded) : hash_or_encoded if decoded == ''.b NullNode::NULL elsif decoded.size == 2 key, value = decoded nibbles = Nibbles.decode_nibbles(key) if Nibbles.is_nibbles_terminated?(nibbles) Leaf.new(key, value) else Extension.new(key, value) end elsif decoded.size == 17 Branch.new(decoded) else raise InvalidNode.new("can't determine node type: #{Utils.to_hex hash_or_encoded}") end end def compute_leaf_key(nibbles) Nibbles.encode_nibbles(Nibbles.add_nibbles_terminator(nibbles)) end def compute_extension_key(nibbles) Nibbles.encode_nibbles(nibbles) end def get_common_prefix_length(left_key, right_key) left_key.zip(right_key).each_with_index do |(l_nibble, r_nibble), i| return i if l_nibble != r_nibble end [left_key.size, right_key.size].min end def consume_common_prefix(left_key, right_key) common_prefix_length = get_common_prefix_length(left_key, right_key) common_prefix = left_key[0...common_prefix_length] left_reminder = left_key[common_prefix_length..-1] right_reminder = right_key[common_prefix_length..-1] [common_prefix, left_reminder, right_reminder] end end end class NullNode < Node NULL = NullNode.new def initialize raise NotImplementedError if @singleton @singleton = true end def null? true end def self.rlp_encode(_) RLP.encode(''.b) end def to_s ''.b end end class Branch < Node class << self def new_with_value(branches: [NullNode::NULL] * 16, value:) new(branches + [value]) end end extend Forwardable def_delegators :@branches, :[], :[]=, :each, :all?, :any? attr_reader :branches def initialize(branches = [NullNode::NULL] * 16 + [''.b]) raise InvalidNode.new('branches size should be 17') if branches.size != 17 @branches = branches end def value self[16] end def branch? true end def self.rlp_encode(node) RLP.encode_simple(node.branches) end end class Extension < Node attr_reader :key, :node_hash def initialize(key, node_hash) @key = key @node_hash = node_hash end def extract_key Nibbles.remove_nibbles_terminator(Nibbles.decode_nibbles key) end def self.rlp_encode(node) RLP.encode_simple([node.key, node.node_hash]) end end class Leaf < Node attr_reader :key, :value def initialize(key, value) @key = key @value = value end def extract_key Nibbles.remove_nibbles_terminator(Nibbles.decode_nibbles key) end def self.rlp_encode(node) RLP.encode_simple([node.key, node.value]) end end BLANK_NODE_HASH = Utils.keccak(RLP.encode(''.b)).freeze end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/trie/nibbles.rb
lib/ciri/trie/nibbles.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri class Trie module Nibbles NIBBLE_TERMINATOR = 16 HP_FLAG_2 = 2 HP_FLAG_0 = 0 extend self def decode_nibbles(value) nibbles_with_flag = bytes_to_nibbles(value) flag = nibbles_with_flag[0] needs_terminator = [HP_FLAG_2, HP_FLAG_2 + 1].include? flag is_odd_length = [HP_FLAG_0 + 1, HP_FLAG_2 + 1].include? flag raw_nibbles = if is_odd_length nibbles_with_flag[1..-1] else nibbles_with_flag[2..-1] end if needs_terminator add_nibbles_terminator(raw_nibbles) else raw_nibbles end end def encode_nibbles(nibbles) flag = if is_nibbles_terminated?(nibbles) HP_FLAG_2 else HP_FLAG_0 end raw_nibbles = remove_nibbles_terminator(nibbles) flagged_nibbles = if raw_nibbles.size.odd? [flag + 1] + raw_nibbles else [flag, 0] + raw_nibbles end nibbles_dehex(flagged_nibbles) end def remove_nibbles_terminator(nibbles) return nibbles[0..-2] if is_nibbles_terminated?(nibbles) nibbles end def bytes_to_nibbles(value) hex_s = Utils.hex(value) hex_s = hex_s[2..-1] if hex_s.start_with?('0x') hex_s.each_char.map {|c| c.to_i(16)} end def nibbles_dehex(nibbles) Utils.dehex(nibbles.map {|n| n.to_s(16)}.join) end def is_nibbles_terminated?(nibbles) nibbles && nibbles[-1] == NIBBLE_TERMINATOR end def add_nibbles_terminator(nibbles) if is_nibbles_terminated?(nibbles) nibbles else nibbles + [NIBBLE_TERMINATOR] end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/db/account_db.rb
lib/ciri/db/account_db.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/core_ext' require 'ciri/trie' require 'ciri/types/account' require 'ciri/serialize' require 'ciri/utils/logger' using Ciri::CoreExt module Ciri module DB class AccountDB include Serialize include Utils::Logger attr_reader :db def initialize(db, root_hash: nil) @db = db root_hash ||= Trie::BLANK_NODE_HASH @trie = Trie.new(db: @db, root_hash: root_hash, prune: false) end def root_hash @trie.root_hash end def store(address, key, value) account = find_account address trie = Trie.new(db: @db, root_hash: account.storage_root) debug("#{address.hex}[#{key}] -> #{value}") converted_key = convert_key Utils.big_endian_encode(key, size: 32) if value && value != 0 trie[converted_key] = RLP.encode(value) else trie.delete(converted_key) end account.storage_root = trie.root_hash update_account(address, account) end def fetch(address, key) # remove unnecessary null byte from key converted_key = convert_key Utils.big_endian_encode(key, size: 32) account = find_account address trie = Trie.new(db: @db, root_hash: account.storage_root) value = trie[converted_key] value.empty? ? 0 : RLP.decode(value, Integer) end def set_nonce(address, nonce) account = find_account(address) account.nonce = nonce update_account(address, account) end def increment_nonce(address, value = 1) account = find_account(address) account.nonce += value update_account(address, account) end def set_balance(address, balance) account = find_account(address) account.balance = balance update_account(address, account) end def add_balance(address, value) account = find_account(address) account.balance += value raise "value can't be negative" if account.balance < 0 update_account(address, account) end def set_account_code(address, code) code ||= ''.b account = find_account(address) account.code_hash = Utils.keccak(code) update_account(address, account) db[account.code_hash] = code end def get_account_code(address) db[find_account(address).code_hash] || ''.b end def find_account(address) rlp_encoded_account = @trie[convert_key address] if rlp_encoded_account.nil? || rlp_encoded_account.size == 0 Types::Account.new_empty else Types::Account.rlp_decode(rlp_encoded_account) end end def account_exist?(address) rlp_encoded_account = @trie[convert_key address] non_exists = rlp_encoded_account.nil? || rlp_encoded_account.size == 0 !non_exists end def delete_account(address) debug "delete #{address.to_s.hex}" @trie.delete(convert_key address) end def account_dead?(address) find_account(address).empty? end private def update_account(address, account) debug 'update account' debug address.hex debug account.serializable_attributes @trie[convert_key address] = Types::Account.rlp_encode account end def convert_key(key) Utils.keccak key.to_s end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/db/backend/rocks.rb
lib/ciri/db/backend/rocks.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'forwardable' require_relative 'rocks_db' require_relative 'errors' module Ciri module DB module Backend # implement kvstore class Rocks extend Forwardable def initialize(path) @db = RocksDB::DB.new(path) end def_delegators :db, :get, :put, :[], :[]=, :delete def fetch(key) value = self[key] raise KeyError.new("key not found: #{key.inspect}") if value.nil? value end def include?(key) !self[key].nil? end def each(&blk) inter_each(only_key: false, &blk) end def keys(key: nil) inter_each(key: key, only_key: true) end def scan(key, &blk) inter_each(key: key, only_key: false, &blk) end def batch batch = RocksDB::Batch.new yield batch db.write(batch) self end def close return if closed? db.close @db = nil end def closed? @db.nil? end private def db @db || raise(InvalidError.new 'db is not open') end def inter_each(key: nil, only_key: true, &blk) i = db.new_iterator key ? i.seek(key) : i.seek_to_first enum = Enumerator.new do |iter| while i.valid iter << (only_key ? i.key : [i.key, i.value]) i.next end ensure i.close end if blk.nil? enum else enum.each(&blk) self end end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/db/backend/memory.rb
lib/ciri/db/backend/memory.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'forwardable' require_relative 'errors' module Ciri module DB module Backend # implement kvstore class Memory class Batch attr_reader :value def initialize @value = Hash.new end def put(k, v) @value[k] = v end end extend Forwardable def initialize @db = {} end def initialize_copy(orig) super @db = orig.instance_variable_get(:@db).dup end def_delegators :db, :[], :[]=, :fetch, :delete, :include? def get(key) db[key] end def put(key, value) db[key] = value end def batch b = Batch.new yield(b) db.merge! b.value end def close @db = nil end def closed? @db.nil? end private def db @db || raise(InvalidError.new 'db is closed') end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/db/backend/errors.rb
lib/ciri/db/backend/errors.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri module DB module Backend class InvalidError < StandardError end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/db/backend/rocks_db.rb
lib/ciri/db/backend/rocks_db.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ffi' module Ciri module DB module Backend module RocksDB class Error < StandardError end module RocksDBLib extend FFI::Library ffi_lib 'rocksdb' attach_function :rocksdb_options_create, [], :pointer attach_function :rocksdb_options_set_create_if_missing, [:pointer, :int], :void attach_function :rocksdb_open, [:pointer, :string, :pointer], :pointer attach_function :rocksdb_close, [:pointer], :void attach_function :rocksdb_writeoptions_create, [], :pointer attach_function :rocksdb_readoptions_create, [], :pointer attach_function :rocksdb_writeoptions_destroy, [:pointer], :void attach_function :rocksdb_readoptions_destroy, [:pointer], :void attach_function :rocksdb_options_destroy, [:pointer], :void attach_function :rocksdb_put, [:pointer, :pointer, :pointer, :int, :pointer, :int, :pointer], :void attach_function :rocksdb_get, [:pointer, :pointer, :pointer, :int, :pointer, :pointer], :pointer attach_function :rocksdb_delete, [:pointer, :pointer, :pointer, :int, :pointer], :void attach_function :rocksdb_write, [:pointer, :pointer, :pointer, :pointer], :void # iterator attach_function :rocksdb_create_iterator, [:pointer, :pointer], :pointer attach_function :rocksdb_iter_destroy, [:pointer], :void attach_function :rocksdb_iter_valid, [:pointer], :uchar attach_function :rocksdb_iter_seek_to_first, [:pointer], :void attach_function :rocksdb_iter_seek_to_last, [:pointer], :void attach_function :rocksdb_iter_seek, [:pointer, :string, :int], :void attach_function :rocksdb_iter_seek_for_prev, [:pointer, :string, :int], :void attach_function :rocksdb_iter_next, [:pointer], :void attach_function :rocksdb_iter_prev, [:pointer], :void attach_function :rocksdb_iter_key, [:pointer, :pointer], :string attach_function :rocksdb_iter_value, [:pointer, :pointer], :string # batch attach_function :rocksdb_writebatch_create, [], :pointer attach_function :rocksdb_writebatch_destroy, [:pointer], :void attach_function :rocksdb_writebatch_put, [:pointer, :pointer, :int, :pointer, :int], :void attach_function :rocksdb_writebatch_delete, [:pointer, :string, :int], :void attach_function :rocksdb_writebatch_count, [:pointer], :int class << self def open_database(path, options) err_ptr = FFI::MemoryPointer.new :string db = rocksdb_open(options, path, err_ptr) raise_error_from_point(Error, err_ptr) db end def close_database(db) rocksdb_close(db) nil end def put(db, write_options, key, value) err_ptr = FFI::MemoryPointer.new :pointer # use pointer to aboid ffi null string issue key_ptr = FFI::MemoryPointer.from_string(key) value_ptr = FFI::MemoryPointer.from_string(value) rocksdb_put(db, write_options, key_ptr, key.size, value_ptr, value.size + 1, err_ptr) raise_error_from_point(Error, err_ptr) nil end def get(db, read_options, key) err_ptr = FFI::MemoryPointer.new :pointer value_len = FFI::MemoryPointer.new :int value_ptr = RocksDBLib.rocksdb_get(db, read_options, key, key.size, value_len, err_ptr) raise_error_from_point(Error, err_ptr) len = value_len.read_int - 1 key_exists = len > 0 && !value_ptr.null? key_exists ? value_ptr.read_string(len) : nil end def delete(db, write_options, key) key_ptr = FFI::MemoryPointer.from_string(key) err_ptr = FFI::MemoryPointer.new :pointer RocksDBLib.rocksdb_delete(db, write_options, key_ptr, key.size, err_ptr) raise_error_from_point(Error, err_ptr) nil end def write(db, write_options, batch) err_ptr = FFI::MemoryPointer.new :pointer RocksDBLib.rocksdb_write(db, write_options, batch, err_ptr) raise_error_from_point(Error, err_ptr) nil end def writebatch_put(batch, key, value) key_ptr = FFI::MemoryPointer.from_string(key) value_ptr = FFI::MemoryPointer.from_string(value) rocksdb_writebatch_put(batch, key_ptr, key.size, value_ptr, value.size + 1) nil end def writebatch_delete(batch, key) rocksdb_writebatch_delete(batch, key, key.size) nil end private def raise_error_from_point(error_klass, err_ptr) err = err_ptr.get_pointer(0) raise error_klass.new(err.read_string_to_null) unless err.null? end end end class Batch def initialize @batch = RocksDBLib.rocksdb_writebatch_create ObjectSpace.define_finalizer(self, self.class.finalizer(@batch)) end def put(key, value) RocksDBLib.writebatch_put(@batch, key, value) end def delete(key) RocksDBLib.writebatch_delete(@batch, key) end def raw_batch @batch end class << self def finalizer(batch) proc { RocksDBLib.rocksdb_writebatch_destroy(batch) } end end end class Iterator def initialize(db, readoptions) @iter = RocksDBLib.rocksdb_create_iterator(db, readoptions) end def valid RocksDBLib.rocksdb_iter_valid(@iter) == 1 end def seek_to_first RocksDBLib.rocksdb_iter_seek_to_first(@iter) nil end def seek_to_last RocksDBLib.rocksdb_iter_seek_to_last(@iter) nil end def seek(key) RocksDBLib.rocksdb_iter_seek(@iter, key, key.size) nil end def seek_for_prev(key) RocksDBLib.rocksdb_iter_seek_for_prev(@iter, key, key.size) nil end def next RocksDBLib.rocksdb_iter_next(@iter) nil end def prev RocksDBLib.rocksdb_iter_prev(@iter) nil end def key len_ptr = FFI::MemoryPointer.new :int key = RocksDBLib.rocksdb_iter_key(@iter, len_ptr) len = len_ptr.read_int key[0...len] end def value len_ptr = FFI::MemoryPointer.new :int value = RocksDBLib.rocksdb_iter_value(@iter, len_ptr) len = len_ptr.read_int value[0...len] end def close RocksDBLib.rocksdb_iter_destroy(@iter) end end class DB def initialize(path) options = RocksDBLib.rocksdb_options_create RocksDBLib.rocksdb_options_set_create_if_missing(options, 1) @db = RocksDBLib.open_database(path, options) @writeoptions = RocksDBLib.rocksdb_writeoptions_create @readoptions = RocksDBLib.rocksdb_readoptions_create ObjectSpace.define_finalizer(self, self.class.finalizer(@db, options, @writeoptions, @readoptions)) end def get(key) RocksDBLib.get(@db, @readoptions, key) end alias [] get def put(key, value) RocksDBLib.put(@db, @writeoptions, key, value) end alias []= put def delete(key) RocksDBLib.delete(@db, @writeoptions, key) end def new_iterator Iterator.new(@db, @readoptions) end def close RocksDBLib.close_database(@db) if @db @db = nil end def closed? @db.nil? end def write(batch) RocksDBLib.write(@db, @writeoptions, batch.raw_batch) end class << self def finalizer(db, options, write_options, read_options) proc { # RocksDBLib.close_database(db) RocksDBLib.rocksdb_options_destroy(options) RocksDBLib.rocksdb_writeoptions_destroy(write_options) RocksDBLib.rocksdb_readoptions_destroy(read_options) } end end end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/pow_chain/header_chain.rb
lib/ciri/pow_chain/header_chain.rb
# HeaderChain # store headers module Ciri module POWChain class HeaderChain HEAD = 'head' GENESIS = 'genesis' HEADER_PREFIX = 'h' TD_SUFFIX = 't' NUM_SUFFIX = 'n' attr_reader :store def initialize(store, fork_config: nil) @store = store @fork_config = fork_config end def head encoded = store[HEAD] encoded && Header.rlp_decode(encoded) end def head=(header) store[HEAD] = header.rlp_encode end def get_header(hash) encoded = store[HEADER_PREFIX + hash] encoded && Header.rlp_decode(encoded) end def get_header_by_number(number) hash = get_header_hash_by_number(number) hash && get_header(hash) end def valid?(header) # ignore genesis header if there not exist one return true if header.number == 0 && get_header_by_number(0).nil? parent_header = get_header(header.parent_hash) return false unless parent_header # check height return false unless parent_header.number + 1 == header.number # check timestamp return false unless parent_header.timestamp < header.timestamp # check gas limit range parent_gas_limit = parent_header.gas_limit gas_limit_max = parent_gas_limit + parent_gas_limit / 1024 gas_limit_min = parent_gas_limit - parent_gas_limit / 1024 gas_limit = header.gas_limit return false unless gas_limit >= 5000 && gas_limit > gas_limit_min && gas_limit < gas_limit_max return false unless calculate_difficulty(header, parent_header) == header.difficulty # check pow_chain begin POW.check_pow(header.number, header.mining_hash, header.mix_hash, header.nonce, header.difficulty) rescue POW::InvalidError return false end true end # calculate header difficulty # you can find explain in Ethereum yellow paper: Block Header Validity section. def calculate_difficulty(header, parent_header) return header.difficulty if header.number == 0 fork_schema = @fork_config.choose_fork(header.number) fork_schema.calculate_difficulty(header, parent_header) end # write header def write(header) hash = header.get_hash # get total difficulty td = if header.number == 0 header.difficulty else parent_header = get_header(header.parent_hash) raise "can't find parent from db" unless parent_header parent_td = total_difficulty(parent_header.get_hash) parent_td + header.difficulty end # write header and td store.batch do |b| b.put(HEADER_PREFIX + hash, header.rlp_encode) b.put(HEADER_PREFIX + hash + TD_SUFFIX, RLP.encode(td, Integer)) end end def write_header_hash_number(header_hash, number) enc_number = Utils.big_endian_encode number store[HEADER_PREFIX + enc_number + NUM_SUFFIX] = header_hash end def get_header_hash_by_number(number) enc_number = Utils.big_endian_encode number store[HEADER_PREFIX + enc_number + NUM_SUFFIX] end def total_difficulty(header_hash = head.nil? ? nil : head.get_hash) return 0 if header_hash.nil? RLP.decode(store[HEADER_PREFIX + header_hash + TD_SUFFIX], Integer) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/pow_chain/chain.rb
lib/ciri/pow_chain/chain.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'forwardable' require 'ciri/evm' require 'ciri/state' require 'ciri/utils/logger' require 'ciri/forks' require 'ciri/types/receipt' require_relative 'header_chain' require_relative 'block' require_relative 'header' require_relative 'transaction' require_relative 'pow' module Ciri module POWChain # Chain manipulate logic # store via rocksdb class Chain include Ciri::Utils::Logger class Error < StandardError end class InvalidHeaderError < Error end class InvalidBlockError < Error end extend Forwardable BODY_PREFIX = 'b' def_delegators :@header_chain, :head, :total_difficulty, :get_header_by_number, :get_header attr_reader :genesis, :network_id, :store, :header_chain def initialize(store, genesis:, network_id:, fork_config:) @store = store @header_chain = HeaderChain.new(store, fork_config: fork_config) @genesis = genesis @network_id = network_id @fork_config = fork_config load_or_init_store end # run block def import_block(block, validate: true) debug("import block #{block.header.number}") validate_block(block) if validate write_block(block) # update state # apply_changes end # validate block, effect current state def validate_block(block) raise InvalidBlockError.new('invalid header') unless @header_chain.valid?(block.header) # valid ommers raise InvalidBlockError.new('ommers blocks can not more than 2') if block.ommers.size > 2 block.ommers.each do |ommer| unless is_kin?(ommer, get_block(block.header.parent_hash), 6) raise InvalidBlockError.new("invalid ommer relation") end end parent_header = @header_chain.get_header(block.header.parent_hash) state = State.new(store, state_root: parent_header.state_root) evm = EVM.new(state: state, chain: self, fork_schema: @fork_config.choose_fork(block.header.number)) # valid transactions and gas begin receipts = evm.transition(block) rescue EVM::InvalidTransition => e raise InvalidBlockError.new(e.message) end # verify state root if evm.state_root != block.header.state_root error("incorrect state_root, evm: #{Utils.hex evm.state_root}, header: #{Utils.hex block.header.state_root} height: #{block.header.number}") raise InvalidBlockError.new("incorrect state_root") end # verify receipts root trie = Trie.new receipts.each_with_index do |r, i| trie[RLP.encode(i)] = RLP.encode(r) end if trie.root_hash != block.header.receipts_root raise InvalidBlockError.new("incorrect receipts_root") end # verify state root trie = Trie.new block.transactions.each_with_index do |t, i| trie[RLP.encode(i)] = RLP.encode(t) end if trie.root_hash != block.header.transactions_root raise InvalidBlockError.new("incorrect transactions_root") end end def genesis_hash genesis.header.get_hash end def current_block get_block(head.get_hash) end def current_height head.number end # insert blocks in order # blocks must be ordered from lower height to higher height def insert_blocks(blocks, validate: true) prev_block = blocks[0] blocks[1..-1].each do |block| unless block.number == prev_block.number + 1 && block.parent_hash == prev_block.get_hash raise InvalidBlockError.new("blocks insert orders not correct") end end blocks.each do |block| import_block(block, validate: validate) end end def get_block_by_number(number) hash = @header_chain.get_header_hash_by_number(number) hash && get_block(hash) end def get_block(hash) encoded = store[BODY_PREFIX + hash] encoded && Block.rlp_decode(encoded) end def write_block(block) # write header header = block.header # raise InvalidHeaderError.new("invalid header: #{header.number}") unless @header_chain.valid?(header) @header_chain.write(header) # write body store[BODY_PREFIX + header.get_hash] = block.rlp_encode td = total_difficulty(header.get_hash) if td > total_difficulty # new block not follow current head, need reorg chain if head && ((header.number <= head.number) || (header.number == head.number + 1 && header.parent_hash != head.get_hash)) reorg_chain(block, current_block) else # otherwise, new block extend current chain, just update chain head @header_chain.head = header @header_chain.write_header_hash_number(header.get_hash, header.number) end end end private def is_kin?(ommer, parent, n) return false if parent.nil? return false if n == 0 return true if get_header(ommer.parent_hash) == get_header(parent.header.parent_hash) && ommer != parent.header && !parent.ommers.include?(ommer) is_kin?(ommer, get_block(parent.header.parent_hash), n - 1) end # reorg chain def reorg_chain(new_block, old_block) new_chain = [] # find common ancestor block # move new_block and old_block to same height while new_block.number > old_block.number new_chain << new_block new_block = get_block(new_block.parent_hash) end while old_block.number > new_block.number old_block = get_block(old_block.parent_hash) end while old_block.get_hash != new_block.get_hash new_chain << new_block old_block = get_block(old_block.parent_hash) new_block = get_block(new_block.parent_hash) end # rewrite chain new_chain.reverse_each {|block| rewrite_block(block)} end # rewrite block # this method will treat block as canonical chain block def rewrite_block(block) @header_chain.head = block.header @header_chain.write_header_hash_number(block.get_hash, block.number) end def load_or_init_store # write genesis block, is chain head not exists if head.nil? write_block(genesis) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/pow_chain/pow.rb
lib/ciri/pow_chain/pow.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils' require 'lru_redux' require 'concurrent' require 'ethash' module Ciri module POWChain # Ethash POW # see py-evm https://github.com/ethereum/py-evm/blob/026553da69bbea314fe26c8c34d453f66bfb4d30/evm/consensus/pow.py module POW EPOCH_LENGTH = 30000 extend self class Error < StandardError end class InvalidError < Error end class GivingUpError < Error end # thread safe caches @cache_seeds = Concurrent::Array.new(['\x00'.b * 32]) @cache_by_seed = LruRedux::ThreadSafeCache.new(10) def get_cache(block_number) epoch = block_number / EPOCH_LENGTH while @cache_seeds.size <= epoch @cache_seeds.append(Utils.keccak(@cache_seeds[-1])) end seed = @cache_seeds[epoch] @cache_by_seed.getset(seed) do Ethash.mkcache_bytes(block_number) end end def check_pow(block_number, mining_hash, mix_hash, nonce_bytes, difficulty) raise ArgumentError.new "mix_hash.length must equal to 32" if mix_hash.size != 32 raise ArgumentError.new "mining_hash.length must equal to 32" if mining_hash.size != 32 raise ArgumentError.new "nonce.length must equal to 8" if nonce_bytes.size != 8 cache = get_cache(block_number) output = Ethash.hashimoto_light(block_number, cache, mining_hash, Utils.big_endian_decode(nonce_bytes)) if output[:mixhash] != mix_hash raise InvalidError.new("mix hash mismatch; #{Utils.hex(output[:mixhash])} != #{Utils.hex(mix_hash)}") end result = Utils.big_endian_decode(output[:result]) unless result < 2 ** 256 / difficulty raise InvalidError.new("difficulty not enough, need difficulty #{difficulty}, but result #{result}") end end MAX_TEST_MINE_ATTEMPTS = 1000 def mine_pow_nonce(block_number, mining_hash, difficulty) cache = get_cache(block_number) MAX_TEST_MINE_ATTEMPTS.times do |nonce| output = Ethash.hashimoto_light(block_number, cache, mining_hash, nonce) result = Utils.big_endian_decode(output[:result]) result_cap = 2 ** 256 / difficulty return [output[:mixhash], Utils.big_endian_encode(nonce).rjust(8, "\x00")] if result <= result_cap end raise GivingUpError.new("tries too many times, giving up") end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/pow_chain/transaction.rb
lib/ciri/pow_chain/transaction.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'ciri/crypto' require 'ciri/key' require 'ciri/types/address' require 'ciri/types/uint' module Ciri module POWChain class Transaction include Types class InvalidError < StandardError end EIP155_CHAIN_ID_OFFSET = 35 V_OFFSET = 27 include RLP::Serializable schema( nonce: Integer, gas_price: Integer, gas_limit: Integer, to: Address, value: Integer, data: RLP::Bytes, v: Integer, r: Integer, s: Integer ) default_data v: 0, r: 0, s: 0, data: "\x00".b # sender address # @return address String def sender @sender ||= begin address = Key.ecdsa_recover(sign_hash(chain_id), signature).to_address address.validate address end end def signature v = if eip_155_signed_transaction? # retrieve actually v from transaction.v, see EIP-155(prevent replay attack) (self.v - 1) % 2 elsif [27, 28].include?(self.v) self.v - 27 else self.v end Crypto::Signature.new(vrs: [v, r, s]) end # @param key Key def sign_with_key!(key) signature = key.ecdsa_signature(sign_hash) self.v = signature.v self.r = signature.r self.s = signature.s nil end def contract_creation? to.empty? end def sign_hash(chain_id = nil) param = data || ''.b list = [nonce, gas_price, gas_limit, to, value, param] if chain_id list += [chain_id, ''.b, ''.b] end Utils.keccak(RLP.encode_simple list) end def get_hash Utils.keccak rlp_encode end # validate transaction def validate! raise NotImplementedError end def validate_sender! begin sender rescue Ciri::Crypto::ECDSASignatureError => e raise InvalidError.new("recover signature error, error: #{e}") rescue Ciri::Types::Errors::InvalidError => e raise InvalidError.new(e.to_s) end end # return chain_id by v def chain_id if eip_155_signed_transaction? # retrieve chain_id from v, see EIP-155 (v - 35) / 2 end end # https://github.com/ethereum/EIPs/blob/984cf5de90bbf5fbe7e49be227b0c2f9567e661e/EIPS/eip-155.md def eip_155_signed_transaction? v >= EIP155_CHAIN_ID_OFFSET end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/pow_chain/header.rb
lib/ciri/pow_chain/header.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' module Ciri module POWChain # block header class Header include RLP::Serializable schema( parent_hash: RLP::Bytes, ommers_hash: RLP::Bytes, beneficiary: RLP::Bytes, state_root: RLP::Bytes, transactions_root: RLP::Bytes, receipts_root: RLP::Bytes, logs_bloom: RLP::Bytes, difficulty: Integer, number: Integer, gas_limit: Integer, gas_used: Integer, timestamp: Integer, extra_data: RLP::Bytes, mix_hash: RLP::Bytes, nonce: RLP::Bytes, ) # header hash def get_hash Utils.keccak(rlp_encode) end # mining_hash, used for mining def mining_hash Utils.keccak(rlp_encode skip_keys: [:mix_hash, :nonce]) end def inspect h = {} self.class.schema.keys.each do |key| key_schema = self.class.schema[key] h[key] = if key_schema.type == RLP::Bytes Utils.hex serializable_attributes[key] else serializable_attributes[key] end end h end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/pow_chain/block.rb
lib/ciri/pow_chain/block.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require_relative 'header' require_relative 'transaction' require 'forwardable' module Ciri module POWChain # structure for ethereum block class Block include RLP::Serializable schema( header: Header, transactions: [Transaction], ommers: [Header], # or uncles ) extend Forwardable def_delegators :header, :number, :get_hash, :mining_hash, :parent_hash end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/beacon_chain/attestation_record.rb
lib/ciri/beacon_chain/attestation_record.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'ciri/types/int' require 'ciri/types/hash' require 'ciri/types/bytes' require 'ciri/types/address' require 'forwardable' module Ciri module BeaconChain class AttestationRecord include RLP::Serializable include Types schema( slot: Int64, shard_id: Int16, oblique_parent_hashes: [Hash32], shard_block_hash: Hash32, attester_bitfield: Bytes, aggregate_sig: [Int256], ) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/beacon_chain/shard_and_committee.rb
lib/ciri/beacon_chain/shard_and_committee.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'ciri/types/int' require 'ciri/types/hash' require 'ciri/types/bytes' require 'ciri/types/address' require 'forwardable' require_relative 'validator_record' module Ciri module BeaconChain class ShardAndCommittee include RLP::Serializable include Types schema( shard_id: [ValidatorRecord], committee: [Int24], ) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/beacon_chain/crystallized_state.rb
lib/ciri/beacon_chain/crystallized_state.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'ciri/types/int' require 'ciri/types/hash' require 'ciri/types/bytes' require 'ciri/types/address' require 'forwardable' require_relative 'validator_record' require_relative 'shard_and_committee' require_relative 'crosslink_record' module Ciri module BeaconChain class CrystallizedState include RLP::Serializable include Types schema( validators: [ValidatorRecord], last_state_recalc: [Int64], indices_for_slots: [[ShardAndCommittee]], last_justified_slot: Int64, justified_streak: Int64, last_finalized_slot: Int64, current_dynasty: Int64, crosslinking_start_shard: Int16, crosslink_records: [CrosslinkRecord], total_deposits: Int256, dynasty_seed: Hash32, dynasty_seed_last_reset: Int64, ) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/beacon_chain/active_state.rb
lib/ciri/beacon_chain/active_state.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'ciri/types/int' require 'ciri/types/hash' require 'ciri/types/bytes' require 'ciri/types/address' require 'forwardable' require_relative 'attestation_record' module Ciri module BeaconChain class ActiveState include RLP::Serializable include Types schema( pending_attestations: [AttestationRecord], recent_block_hashes: [Hash32], ) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/beacon_chain/chain.rb
lib/ciri/beacon_chain/chain.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'forwardable' require 'ciri/core_ext' require 'ciri/state' require 'ciri/utils/logger' require 'ciri/shasper/constants' require_relative 'errors' using Ciri::CoreExt module Ciri module BeaconChain # Chain manipulate logic # store via rocksdb class Chain include Shasper::Constants include Ciri::Utils::Logger extend Forwardable HEAD = 'head'.b GENESIS = 'genesis'.b BODY_PREFIX = 'b'.b NUMBER_SUFFIX = 'n'.b attr_reader :store, :genesis def initialize(store, genesis:) @store = store @genesis = genesis load_or_init_store end # run block def import_block(block, validate: true) debug("import block #{block.header.number}") validate_block(block) if validate write_block(block) end # validate block, effect current state def validate_block(block) # check block ready conditions # 1. parent block must already be accepted. parent_block = get_block(block.parent_hash) raise BlockNotReadyError.new("can't find parent block by hash #{block.parent_hash.to_hex}") unless parent_block # TODO 2. pow_chain_ref block must already be accepted. # 3. local time must greater or equal than minimum timestamp. unless (local_timestamp = Time.now.to_i) >= (minimum_timestamp = genesis_time + block.slot_number * SLOT_DURATION) raise BlockNotReadyError.new("local_timestamp(#{local_timestamp}) must greater than or equal with minimum_timestamp(#{minimum_timestamp})") end end # insert blocks in order # blocks must be ordered from lower height to higher height def insert_blocks(blocks, validate: true) prev_block = blocks[0] blocks[1..-1].each do |block| unless block.number == prev_block.number + 1 && block.parent_hash == prev_block.get_hash raise InvalidBlockError.new("blocks insert orders not correct") end end blocks.each do |block| import_block(block, validate: validate) end end def head encoded = store[HEAD] encoded && Block.rlp_decode(encoded) end alias current_block head def set_head(block, encoded: Block.rlp_encode(block)) store[HEAD] = encoded end def get_block(hash) encoded = store[BODY_PREFIX + hash] encoded && Block.rlp_decode(encoded) end def write_block(block) encoded = Block.rlp_encode(block) store[BODY_PREFIX + block.get_hash] = encoded if fork_choice?(block) reorg_chain(block, current_block) else set_head(encoded: encoded) end end private def fork_choice?(block) # TODO Beacon chain fork choice rule https://notes.ethereum.org/SCIg8AH5SA-O4C1G1LYZHQ# false end # reorg chain def reorg_chain(new_block, old_block) # TODO Beacon chain fork choice rule https://notes.ethereum.org/SCIg8AH5SA-O4C1G1LYZHQ# nil # new_chain = [] # # find common ancestor block # # move new_block and old_block to same height # while new_block.number > old_block.number # new_chain << new_block # new_block = get_block(new_block.parent_hash) # end # # while old_block.number > new_block.number # old_block = get_block(old_block.parent_hash) # end # # while old_block.get_hash != new_block.get_hash # new_chain << new_block # old_block = get_block(old_block.parent_hash) # new_block = get_block(new_block.parent_hash) # end # # # rewrite chain # new_chain.reverse_each {|block| rewrite_block(block)} end def genesis_time # TODO get genesis block timestamp 0 end def load_or_init_store if @genesis.nil? warn "BeaconChain GENESIS block is nil!!!" return end # write genesis block if get_block(@genesis.get_hash).nil? encoded = Block.rlp_encode(@genesis) store[GENESIS] = encoded write_block(@genesis) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/beacon_chain/errors.rb
lib/ciri/beacon_chain/errors.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri module BeaconChain class Error < StandardError end class InvalidBlockError < Error end class BlockNotReadyError < InvalidBlockError end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/beacon_chain/validator_record.rb
lib/ciri/beacon_chain/validator_record.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'ciri/types/int' require 'ciri/types/hash' require 'ciri/types/bytes' require 'ciri/types/address' require 'forwardable' module Ciri module BeaconChain class ValidatorRecord include RLP::Serializable include Types schema( pubkey: Int256, withdrawal_shard: Int16, withdrawal_address: Address, random_commitment: Hash32, balance: Int64, start_dynasty: Int64, end_dynasty: Int64, ) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/beacon_chain/crosslink_record.rb
lib/ciri/beacon_chain/crosslink_record.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'ciri/types/int' require 'ciri/types/hash' require 'ciri/types/bytes' require 'ciri/types/address' require 'forwardable' module Ciri module BeaconChain class CrosslinkRecord include RLP::Serializable include Types schema( dynasty: Int64, block_hash: Hash32, ) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/beacon_chain/block.rb
lib/ciri/beacon_chain/block.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'ciri/types/int' require 'ciri/types/hash' require 'ciri/types/bytes' require 'ciri/types/address' require 'forwardable' require_relative 'attestation_record' module Ciri module BeaconChain # structure for beacon chain block class Block include RLP::Serializable include Types schema( parent_hash: Hash32, slot_number: Int64, randao_reveal: Hash32, attestations: [AttestationRecord], pow_chain_ref: Hash32, active_state_root: Hash32, crystallized_state_root: Hash32, ) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/shasper/constants.rb
lib/ciri/shasper/constants.rb
# Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Shasper module Constants SHARD_COUNT = 1024 DEPOSIT_SIZE = 32 MAX_VALIDATOR_COUNT = 2 ** 22 SLOT_DURATION = 8 CYCLE_LENGTH = 64 MIN_COMMITTEE_SIZE = 128 end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/eth/protocol_messages.rb
lib/ciri/eth/protocol_messages.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/pow_chain/chain' require 'ciri/rlp' require 'stringio' module Ciri module Eth # represent a hash or a number class HashOrNumber attr_reader :value class << self def rlp_encode(item) value = item.value if value.is_a? Integer RLP.encode(value, Integer) else RLP.encode(value) end end def rlp_decode(s) s = StringIO.new(s) if s.is_a?(String) # start with 0xA0, represent s is a 32 length hash bytes c = s.getc s.ungetc(c) if c.ord == 0xa0 RLP.decode(s) else RLP.decode(s, Integer) end end end def initialize(value) @value = value end end # Ethereum Sub-protocol Messages # # class Status include Ciri::RLP::Serializable CODE = 0x00 schema( protocol_version: Integer, network_id: Integer, total_difficulty: Integer, current_block: RLP::Bytes, genesis_block: RLP::Bytes, ) end class GetBlockHeaders include Ciri::RLP::Serializable CODE = 0x03 schema( hash_or_number: HashOrNumber, amount: Integer, skip: Integer, reverse: RLP::Bool, ) end class BlockHeaders CODE = 0x04 attr_reader :headers def initialize(headers:) @headers = headers end def rlp_encode Ciri::RLP.encode(@headers, [POWChain::Header]) end def self.rlp_decode(payload) new headers: Ciri::RLP.decode(payload, [POWChain::Header]) end end class GetBlockBodies CODE = 0x05 attr_reader :hashes def initialize(hashes:) @hashes = hashes end def rlp_encode Ciri::RLP.encode(@hashes) end def self.rlp_decode(payload) new hashes: Ciri::RLP.decode(payload) end end class BlockBodies CODE = 0x06 class Bodies include RLP::Serializable schema( transactions: [POWChain::Transaction], ommers: [POWChain::Header], ) end attr_reader :bodies def initialize(bodies:) @bodies = bodies end def rlp_encode Ciri::RLP.encode(@bodies, [Bodies]) end def self.rlp_decode(bodies) new bodies: Ciri::RLP.decode(bodies, [Bodies]) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/eth/synchronizer.rb
lib/ciri/eth/synchronizer.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'async' require 'async/queue' require 'lru_redux' require 'ciri/utils/logger' module Ciri module Eth # Synchronizer sync blocks with peers class Synchronizer include Ciri::Utils::Logger HEADER_FETCH_COUNT = 10 class PeerEntry attr_reader :header_queue, :body_queue, :peer_context attr_accessor :syncing, :stopping def initialize(peer_context) @peer_context = peer_context @header_queue = Async::Queue.new @body_queue = Async::Queue.new @lru_cache = LruRedux::Cache.new(HEADER_FETCH_COUNT * 2) end def hash @peer_context.hash end def ==(peer_entry) self.class == peer_entry.class && @peer_context == peer_entry.peer_context end def receive_header header_queue.dequeue end def receive_header_in(timeout, task: Async::Task.current) task.timeout(timeout) {header_queue.dequeue} end def receive_body body_queue.dequeue end def receive_body_in(timeout, task: Async::Task.current) task.timeout(timeout) {body_queue.dequeue} end def fetch_peer_header(hash_or_number) cached = @lru_cache[hash_or_number] return cached if cached until header_queue.empty? header = receive_header @lru_cache[header.number] = header @lru_cache[header.get_hash] = header return header if header.number == hash_or_number || header.get_hash == hash_or_number end peer_context.send_msg(GetBlockHeaders, hash_or_number: HashOrNumber.new(hash_or_number), amount: HEADER_FETCH_COUNT, skip: 0, reverse: false) while (header = receive_header_in(10)) @lru_cache[header.number] = header @lru_cache[header.get_hash] = header return header if header.number == hash_or_number || header.get_hash == hash_or_number end raise 'should not touch here' end def fetch_peer_body(hashes) # TODO make sure we received correct message # current implementation assume next received body msg is we request, but we can't make sure # at least make sure the message we received is from same peer we request peer_context.send_msg(GetBlockBodies, hashes: hashes) receive_body_in(10) end end attr_reader :chain def initialize(chain:) @chain = chain @peers = {} super() end def receive_headers(peer, headers) headers.each {|header| @peers[peer].header_queue.enqueue header} end def receive_bodies(peer_context, bodies) @peers[peer_context].body_queue.enqueue bodies end def register_peer(peer_context, task: Async::Task.current) # prevent already exists return if @peers.include?(peer_context) @peers[peer_context] = PeerEntry.new(peer_context) # request block headers if chain td less than peer return unless peer_context.total_difficulty > chain.total_difficulty peer_context.send_msg(GetBlockHeaders, hash_or_number: HashOrNumber.new(peer_context.status.current_block), amount: 1, skip: 0, reverse: true) start_syncing best_peer end def deregister_peer(peer, task: Async::Task.current) peer_entry = @peers.delete(peer) return if peer_entry.nil? || peer_entry.stopping peer_entry.stopping = true end MAX_BLOCKS_SYNCING = 50 # check and start syncing peer def start_syncing(peer, task: Async::Task.current) peer_entry = @peers[peer] return if peer_entry.syncing peer_entry.syncing = true task.async do peer_max_header = peer_header = peer_entry.receive_header local_header = chain.head start_height = [peer_header.number, local_header.number].min # find common height while local_header.get_hash != peer_header.get_hash && !peer_entry.stopping local_header = chain.get_block_by_number start_height peer_header = peer_entry.fetch_peer_header start_height start_height -= 1 end loop do # exit if peer is stopping break if peer_entry.stopping # start from common + 1 block start_height = local_header.number + 1 end_height = [start_height + MAX_BLOCKS_SYNCING, peer_max_header.number].min if start_height < 1 || start_height > end_height raise 'peer is incorrect' end info "Start syncing with Peer##{peer}, from #{start_height} to #{end_height}" (start_height..end_height).each do |height| header = peer_entry.fetch_peer_header height bodies = peer_entry.fetch_peer_body([header.get_hash]) block = POWChain::Block.new(header: header, transactions: bodies[0].transactions, ommers: bodies[0].ommers) # insert to chain.... chain.write_block(block) local_header = header end start_height = end_height + 1 break if end_height >= peer_max_header.number end rescue StandardError => e error("exception occur when syncing with #{peer}, error: #{e}") deregister_peer(peer_entry) end end def best_peer @peers.keys.sort_by(&:total_difficulty).last end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/eth/eth_protocol.rb
lib/ciri/eth/eth_protocol.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/core_ext' require 'ciri/p2p/protocol' require_relative 'peer_context' require_relative 'synchronizer' using Ciri::CoreExt module Ciri module Eth class EthProtocol < P2P::Protocol MAX_RESPONSE_HEADERS = 10 def initialize(name:, version:, length:, chain:) super(name: name, version: version, length: length) @chain = chain end def initialized(context) @synchronizer = Synchronizer.new(chain: @chain) end def connected(context, task: Async::Task.current) peer_context = PeerContext.new(peer: context.peer, context: context) peer_context.send_handshake(1, @chain.total_difficulty, @chain.head.get_hash, @chain.genesis_hash) end def disconnected(context, task: Async::Task.current) peer_context = PeerContext.new(peer: context.peer, context: context) @synchronizer.deregister_peer(peer_context) end def received(context, msg, task: Async::Task.current) peer_context = PeerContext.new(peer: context.peer, context: context) case msg.code when Status::CODE status = Status.rlp_decode(msg.payload) peer_context.set_status(status) @synchronizer.register_peer(peer_context) when GetBlockHeaders::CODE get_header_msg = GetBlockHeaders.rlp_decode(msg.payload) hash_or_number = get_header_msg.hash_or_number header = if hash_or_number.is_a?(Integer) @chain.get_header_by_number hash_or_number else @chain.get_header hash_or_number end headers = [] if header amount = [MAX_RESPONSE_HEADERS, get_header_msg.amount].min # skip get_header_msg.skip.times do next_header = @chain.get_header_by_number header.number + 1 break if next_header.nil? || next_header.parent_hash != header.get_hash header = next_header end amount.times do headers << header next_header = @chain.get_header_by_number header.number + 1 break if next_header.nil? || next_header.parent_hash != header.get_hash header = next_header end header.reverse! if get_header_msg.reverse end headers_msg = BlockHeaders.new(headers: headers).rlp_encode context.send_data(BlockHeaders::CODE, headers_msg) when BlockHeaders::CODE headers = BlockHeaders.rlp_decode(msg.payload).headers unless headers.empty? task.async {@synchronizer.receive_headers(peer_context, headers)} end when BlockBodies::CODE bodies = BlockBodies.rlp_decode(msg.payload).bodies unless bodies.empty? task.async {@synchronizer.receive_bodies(peer_context, bodies)} end else raise StandardError, "unknown code #{msg.code}, #{msg}" end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/lib/ciri/eth/peer_context.rb
lib/ciri/eth/peer_context.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/pow_chain/chain' require 'forwardable' require_relative 'protocol_messages' module Ciri module Eth # eth protocol peer class PeerContext attr_reader :total_difficulty, :status, :peer extend Forwardable def_delegators :@peer, :to_s, :hash def initialize(peer:, context:) @total_difficulty = nil @peer = peer @context = context end # do eth protocol handshake and return status def send_handshake(network_id, total_difficulty, head_hash, genesis_hash) status = Status.new(protocol_version: 63, network_id: network_id, total_difficulty: total_difficulty, current_block: head_hash, genesis_block: genesis_hash) @context.send_data(Status::CODE, status.rlp_encode) end def set_status(status) @status ||= status @total_difficulty = @status.total_difficulty end def send_msg(msg_class, **data) msg = msg_class.new(data) @context.send_data(msg_class::CODE, msg.rlp_encode) end def ==(peer_context) self.class == peer_context.class && peer == peer_context.peer end alias eql? == end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
kurenn/sabisu-rails
https://github.com/kurenn/sabisu-rails/blob/e55dfbd679ac3ec2401178d5f809773f09373bcf/app/helpers/sabisu_rails_helper.rb
app/helpers/sabisu_rails_helper.rb
module SabisuRailsHelper end
ruby
MIT
e55dfbd679ac3ec2401178d5f809773f09373bcf
2026-01-04T17:52:02.123775Z
false
kurenn/sabisu-rails
https://github.com/kurenn/sabisu-rails/blob/e55dfbd679ac3ec2401178d5f809773f09373bcf/app/helpers/sabisu_rails/explorer_helper.rb
app/helpers/sabisu_rails/explorer_helper.rb
module SabisuRails::ExplorerHelper def label_attribute(explorer, attr) explorer.required_attribute?(attr) ? "* #{attr.capitalize}" : attr.capitalize end def active_resource_state(resource) loaded_resource = SabisuRails.default_resource.to_s if params[:explorer].nil? "active" if loaded_resource == resource else "active" if params[:explorer][:resource] == resource end end def prettify_headers(headers) html = "" headers.each do |k, v| k = k.titleize.split(' ').join('-') header_name = content_tag :span, k, class: 'text-muted text-strong' arrow = content_tag :span," <i class='fa fa-long-arrow-right'></i> ".html_safe, class: 'text-muted' header_value = content_tag :span, v, class: 'text-muted' html << (header_name + arrow + header_value) html << "<br />" end html.html_safe end end
ruby
MIT
e55dfbd679ac3ec2401178d5f809773f09373bcf
2026-01-04T17:52:02.123775Z
false
kurenn/sabisu-rails
https://github.com/kurenn/sabisu-rails/blob/e55dfbd679ac3ec2401178d5f809773f09373bcf/app/controllers/sabisu_rails/base_controller.rb
app/controllers/sabisu_rails/base_controller.rb
module SabisuRails class BaseController < ApplicationController layout SabisuRails.layout before_filter :authenticate protected def authenticate authenticate_or_request_with_http_basic do |username, password| username == SabisuRails.authentication_username && password == SabisuRails.authentication_password end end end end
ruby
MIT
e55dfbd679ac3ec2401178d5f809773f09373bcf
2026-01-04T17:52:02.123775Z
false