Top Level Namespace
Constant Summary collapse
- ALCHEMY_URL =
"https://eth-mainnet.g.alchemy.com/v2/alch_PhpVkmsabZhYV69otj1rF"- COINGECKO_URL =
"https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd"- CHAIN_ID =
Ethereum mainnet
1- VERSION =
"0.1.7"- GROUP =
ECDSA::Group::Secp256k1
Instance Method Summary collapse
-
#build_and_sign_tx(private_key_hex, to_address, amount_wei) ⇒ Object
── Transaction signing ─────────────────────────────────────────────────────.
- #cmd_pubkey(args) ⇒ Object
-
#cmd_send(args) ⇒ Object
── Send command ────────────────────────────────────────────────────────────.
- #fetch_eth_price ⇒ Object
-
#generate_private_key ⇒ Object
Generate a random private key: a scalar in [1, n-1] where n is the order of the secp256k1 curve group.
-
#hex_address(raw) ⇒ Object
Derive address (0x-prefixed hex) from a raw 20-byte address string.
-
#keccak256(data) ⇒ Object
── Crypto helpers ──────────────────────────────────────────────────────────.
- #normalize_hex(str) ⇒ Object
- #print_usage ⇒ Object
-
#private_key_to_address(priv_hex) ⇒ Object
Derive the 20-byte address from a private key hex string (with or without 0x).
-
#private_key_to_pubkey(priv_hex) ⇒ Object
Derive the uncompressed public key (04 || x || y, 64 bytes) from a private key hex string (with or without 0x).
-
#rlp_encode(item) ⇒ Object
── RLP Encoding ────────────────────────────────────────────────────────────.
- #rlp_encode_bytes(bytes) ⇒ Object
- #rlp_encode_integer(int) ⇒ Object
- #rlp_encode_list(items) ⇒ Object
-
#rpc_call(method, params = []) ⇒ Object
── JSON-RPC ────────────────────────────────────────────────────────────────.
-
#run_cli(args) ⇒ Object
── CLI dispatch ────────────────────────────────────────────────────────────.
- #show_balance(address) ⇒ Object
-
#show_block_number ⇒ Object
── Display commands ────────────────────────────────────────────────────────.
- #show_new_key ⇒ Object
- #show_price ⇒ Object
- #show_version ⇒ Object
- #to_big_endian(int) ⇒ Object
Instance Method Details
#build_and_sign_tx(private_key_hex, to_address, amount_wei) ⇒ Object
── Transaction signing ─────────────────────────────────────────────────────
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
# File 'lib/eth.rb', line 197 def build_and_sign_tx(private_key_hex, to_address, amount_wei) priv_int = normalize_hex(private_key_hex).to_i(16) sender_pub_point = GROUP.generator.multiply_by_scalar(priv_int) # Derive sender address to match back later for recovery ID sender_raw = private_key_to_address(private_key_hex) # Get nonce sender_hex = "0x#{sender_raw.unpack1('H*')}" nonce_hex = rpc_call("eth_getTransactionCount", [sender_hex, "pending"]) nonce = nonce_hex.to_i(16) # Get gas price gas_price_hex = rpc_call("eth_gasPrice") gas_price = gas_price_hex.to_i(16) gas_limit = 21_000 # standard for a simple ETH transfer value = amount_wei to_bytes = [normalize_hex(to_address)].pack("H*") data = "" amount_eth = value / 1_000_000_000_000_000_000.0 puts "Sender: #{sender_hex}" puts "To: #{to_address}" puts "Amount: #{format('%.18f', amount_eth)} ETH (#{value} wei)" puts "Nonce: #{nonce}" puts "Gas: #{gas_limit}" puts "GasPrice: #{gas_price} wei" puts "" # EIP-155 signing payload: rlp([nonce, gp, gl, to, value, data, chain_id, 0, 0]) signing_list = [nonce, gas_price, gas_limit, to_bytes, value, data, CHAIN_ID, 0, 0] signing_encoded = rlp_encode(signing_list) digest = keccak256(signing_encoded) # Generate random k (temporary key) temp_key = SecureRandom.random_number(GROUP.order - 1) + 1 sig = ECDSA.sign(GROUP, priv_int, digest, temp_key) raise "Signing produced s=0, try again" if sig.nil? # Normalize s to low-s (required by Ethereum) s = sig.s if s > GROUP.order / 2 s = GROUP.order - s end low_sig = ECDSA::Signature.new(sig.r, s) # Determine recovery ID by trying each possible recovered public key rec_id = nil ECDSA.recover_public_key(GROUP, digest, low_sig).each_with_index do |point, i| # Reconstruct raw public key from point xb = to_big_endian(point.x) yb = to_big_endian(point.y) pad32 = ->(b) { b.bytesize >= 32 ? b : "\x00" * (32 - b.bytesize) + b } raw_pub = pad32.call(xb) + pad32.call(yb) addr = keccak256(raw_pub).byteslice(12, 20) if addr == sender_raw rec_id = i break end end raise "Could not determine recovery ID" if rec_id.nil? v = 35 + CHAIN_ID * 2 + rec_id # Signed transaction: rlp([nonce, gp, gl, to, value, data, v, r, s]) # r and s are encoded as integers (not padded byte strings) per Ethereum spec tx_list = [nonce, gas_price, gas_limit, to_bytes, value, data, v, low_sig.r, s] rlp_encode(tx_list) end |
#cmd_pubkey(args) ⇒ Object
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/eth.rb', line 179 def cmd_pubkey(args) if args.empty? puts "Usage: ./eth.rb --pubkey <private_key_hex>" exit 1 end priv_hex = normalize_hex(args[0]) priv = priv_hex.to_i(16) pub_hex = "0x#{private_key_to_pubkey(args[0]).unpack1('H*')}" addr = "0x#{private_key_to_address(args[0]).unpack1('H*')}" puts "Private Key: 0x%064x" % priv puts "Public Key: #{pub_hex}" puts "Address: #{addr}" end |
#cmd_send(args) ⇒ Object
── Send command ────────────────────────────────────────────────────────────
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'lib/eth.rb', line 273 def cmd_send(args) # p args if args.length < 3 puts "Usage: ./eth.rb --send <private_key_hex> <to_address> <amount>" puts " amount: number (ETH) or $number (USD, converted to ETH at current price)" exit 1 end private_key = args[0] to_address = args[1] raw_amount = args[2] exit if raw_amount.to_f == 0 && raw_amount[1..].to_f == 0 # Parse amount: $X → USD, otherwise treat as ETH if raw_amount.start_with?("$") usd_amount = raw_amount[1..].to_f price = fetch_eth_price eth_amount = usd_amount / price puts "Converting $#{format('%.2f', usd_amount)} → #{format('%.8f', eth_amount)} ETH (price: $#{format('%.2f', price)})" else eth_amount = raw_amount.to_f end amount_wei = (eth_amount * 1_000_000_000_000_000_000).to_i # puts "Wei: #{amount_wei}" puts "Building and signing transaction..." signed_tx = build_and_sign_tx(private_key, to_address, amount_wei) tx_hex = "0x#{signed_tx.unpack1('H*')}" puts "Broadcasting..." tx_hash = rpc_call("eth_sendRawTransaction", [tx_hex]) puts "Transaction sent! TxHash: #{tx_hash}" end |
#fetch_eth_price ⇒ Object
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
# File 'lib/eth.rb', line 333 def fetch_eth_price uri = URI(COINGECKO_URL) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri) request["Accept"] = "application/json" response = http.request(request) unless response.code.to_i == 200 puts "HTTP Error: #{response.code} — #{response.}" exit 1 end data = JSON.parse(response.body) unless (price = data.dig("ethereum", "usd")) puts "Could not fetch ETH price" exit 1 end price end |
#generate_private_key ⇒ Object
Generate a random private key: a scalar in [1, n-1] where n is the order of the secp256k1 curve group
167 168 169 |
# File 'lib/eth.rb', line 167 def generate_private_key SecureRandom.random_number(GROUP.order - 1) + 1 end |
#hex_address(raw) ⇒ Object
Derive address (0x-prefixed hex) from a raw 20-byte address string
126 127 128 |
# File 'lib/eth.rb', line 126 def hex_address(raw) "0x#{raw.unpack1('H*')}" end |
#keccak256(data) ⇒ Object
── Crypto helpers ──────────────────────────────────────────────────────────
119 120 121 |
# File 'lib/eth.rb', line 119 def keccak256(data) Digest::Keccak.digest(data, 256) end |
#normalize_hex(str) ⇒ Object
159 160 161 162 163 |
# File 'lib/eth.rb', line 159 def normalize_hex(str) hex = str.start_with?("0x") || str.start_with?("0X") ? str[2..] : str hex = "0#{hex}" if hex.bytesize.odd? hex end |
#print_usage ⇒ Object
367 368 369 370 |
# File 'lib/eth.rb', line 367 def print_usage puts "eth.rb v#{VERSION}" puts File.read(__FILE__)[/^#\sUsage:.*?(?=\n\n)/m] end |
#private_key_to_address(priv_hex) ⇒ Object
Derive the 20-byte address from a private key hex string (with or without 0x)
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
# File 'lib/eth.rb', line 131 def private_key_to_address(priv_hex) priv_int = normalize_hex(priv_hex).to_i(16) pub_point = GROUP.generator.multiply_by_scalar(priv_int) # Uncompressed public key: 04 || x_bytes || y_bytes x_bytes = to_big_endian(pub_point.x) y_bytes = to_big_endian(pub_point.y) # Pad x and y to 32 bytes each pad32 = ->(b) { b.bytesize >= 32 ? b : "\x00" * (32 - b.bytesize) + b } pub_raw = pad32.call(x_bytes) + pad32.call(y_bytes) # Address = last 20 bytes of keccak256(pubkey) hash = keccak256(pub_raw) hash.byteslice(12, 20) end |
#private_key_to_pubkey(priv_hex) ⇒ Object
Derive the uncompressed public key (04 || x || y, 64 bytes) from a private key hex string (with or without 0x)
151 152 153 154 155 156 157 |
# File 'lib/eth.rb', line 151 def private_key_to_pubkey(priv_hex) priv_int = normalize_hex(priv_hex).to_i(16) pub_point = GROUP.generator.multiply_by_scalar(priv_int) pad32 = ->(b) { b.bytesize >= 32 ? b : "\x00" * (32 - b.bytesize) + b } "\x04" + pad32.call(to_big_endian(pub_point.x)) + pad32.call(to_big_endian(pub_point.y)) end |
#rlp_encode(item) ⇒ Object
── RLP Encoding ────────────────────────────────────────────────────────────
66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/eth.rb', line 66 def rlp_encode(item) case item when Integer rlp_encode_integer(item) when String rlp_encode_bytes(item) when Array rlp_encode_list(item) else raise "Unsupported RLP type: #{item.class}" end end |
#rlp_encode_bytes(bytes) ⇒ Object
87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/eth.rb', line 87 def rlp_encode_bytes(bytes) len = bytes.bytesize if len == 1 && bytes.ord < 0x80 bytes elsif len <= 55 (0x80 + len).chr + bytes else len_bytes = to_big_endian(len) (0xb7 + len_bytes.bytesize).chr + len_bytes + bytes end end |
#rlp_encode_integer(int) ⇒ Object
79 80 81 82 83 84 85 |
# File 'lib/eth.rb', line 79 def rlp_encode_integer(int) if int.zero? rlp_encode_bytes("") else rlp_encode_bytes(to_big_endian(int)) end end |
#rlp_encode_list(items) ⇒ Object
99 100 101 102 103 104 105 106 107 108 |
# File 'lib/eth.rb', line 99 def rlp_encode_list(items) encoded = items.map { |i| rlp_encode(i) }.join len = encoded.bytesize if len <= 55 (0xc0 + len).chr + encoded else len_bytes = to_big_endian(len) (0xf7 + len_bytes.bytesize).chr + len_bytes + encoded end end |
#rpc_call(method, params = []) ⇒ Object
── JSON-RPC ────────────────────────────────────────────────────────────────
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/eth.rb', line 31 def rpc_call(method, params = []) uri = URI(ALCHEMY_URL) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true payload = { jsonrpc: "2.0", id: 1, method: method, params: params } request = Net::HTTP::Post.new(uri.path) request.body = JSON.generate(payload) request["Content-Type"] = "application/json" response = http.request(request) unless response.code.to_i == 200 puts "HTTP Error: #{response.code} — #{response.}" exit 1 end result = JSON.parse(response.body) if (error = result["error"]) puts "JSON-RPC Error (#{error['code']}): #{error['message']}" exit 1 end result["result"] end |
#run_cli(args) ⇒ Object
── CLI dispatch ────────────────────────────────────────────────────────────
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 |
# File 'lib/eth.rb', line 374 def run_cli(args) if args.empty? show_block_number elsif args[0] == "--price" show_price elsif args[0] == "--genkey" || args[0] == "-g" show_new_key elsif args[0] == "--pubkey" || args[0] == "pubkey" cmd_pubkey(args[1..]) elsif args[0] == "--version" || args[0] == "-v" show_version elsif args[0] == "--help" || args[0] == "-h" print_usage elsif args[0] == "--send" || args[0] == "send" cmd_send(args[1..]) else show_balance(args[0]) end end |
#show_balance(address) ⇒ Object
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 |
# File 'lib/eth.rb', line 317 def show_balance(address) hex_wei = rpc_call("eth_getBalance", [address, "latest"]) wei = hex_wei.to_i(16) eth = wei / 1_000_000_000_000_000_000.0 # wei → ETH (18 decimals) eth_fmt = format("%.18f", eth) # Fetch ETH/USD price and compute USD value price = fetch_eth_price usd = eth * price usd_fmt = format("%.2f", usd) puts "Address: #{address}" puts "Balance: #{eth_fmt} ETH (#{wei} wei)" puts "Value: $#{usd_fmt} USD @ $#{format("%.2f", price)}/ETH" end |
#show_block_number ⇒ Object
── Display commands ────────────────────────────────────────────────────────
310 311 312 313 314 315 |
# File 'lib/eth.rb', line 310 def show_block_number hex_block = rpc_call("eth_blockNumber") block_num = hex_block.to_i(16) puts "Latest Ethereum block: ##{block_num}" puts "Hex: #{hex_block}" end |
#show_new_key ⇒ Object
171 172 173 174 175 176 177 |
# File 'lib/eth.rb', line 171 def show_new_key priv = generate_private_key priv_hex = "0x%064x" % priv addr = "0x#{private_key_to_address(priv_hex).unpack1('H*')}" puts "Private Key: #{priv_hex}" puts "Address: #{addr}" end |
#show_price ⇒ Object
358 359 360 361 |
# File 'lib/eth.rb', line 358 def show_price price = fetch_eth_price puts "ETH/USD: $#{format("%.2f", price)}" end |
#show_version ⇒ Object
363 364 365 |
# File 'lib/eth.rb', line 363 def show_version puts "eth.rb v#{VERSION}" end |
#to_big_endian(int) ⇒ Object
110 111 112 113 114 115 |
# File 'lib/eth.rb', line 110 def to_big_endian(int) return "" if int.zero? hex = int.to_s(16) hex = "0#{hex}" if hex.bytesize.odd? [hex].pack("H*") end |