pwn 0.5.749 → 0.5.751

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +2 -2
  3. data/documentation/Blockchain.md +107 -9
  4. data/documentation/pwn-ai-Agent.md +310 -4
  5. data/documentation/pwn_silent_help_learn_demo.gif +0 -0
  6. data/etc/default_skills/pwn/banner/SKILL.md +7 -3
  7. data/etc/default_skills/pwn/blockchain/btc/SKILL.md +8 -5
  8. data/etc/default_skills/pwn/blockchain/eth/SKILL.md +12 -3
  9. data/etc/default_skills/pwn/blockchain/eth/references/urls.md +1 -1
  10. data/etc/default_skills/pwn/plugins/repl/SKILL.md +5 -0
  11. data/etc/default_skills/pwn/plugins/repl/ai/SKILL.md +4 -0
  12. data/etc/default_skills/pwn/plugins/repl/ai/references/urls.md +5 -0
  13. data/etc/default_skills/pwn/plugins/repl/ai_console/SKILL.md +48 -0
  14. data/etc/default_skills/pwn/plugins/repl/ai_console_commands/SKILL.md +47 -0
  15. data/etc/default_skills/pwn/plugins/repl/ai_console_usage/SKILL.md +48 -0
  16. data/etc/default_skills/pwn/plugins/repl/ai_swarm/SKILL.md +46 -0
  17. data/lib/pwn/ai/agent/loop.rb +287 -18
  18. data/lib/pwn/ai/agent/swarm.rb +28 -4
  19. data/lib/pwn/ai/open_ai.rb +4 -2
  20. data/lib/pwn/banner.rb +743 -2
  21. data/lib/pwn/blockchain/btc.rb +494 -196
  22. data/lib/pwn/blockchain/eth.rb +440 -81
  23. data/lib/pwn/blockchain.rb +6 -0
  24. data/lib/pwn/config.rb +22 -0
  25. data/lib/pwn/migrate.rb +9 -1
  26. data/lib/pwn/plugins/repl/ai.rb +182 -17
  27. data/lib/pwn/plugins/repl/ai_console.rb +1581 -0
  28. data/lib/pwn/plugins/repl/ai_console_commands.rb +282 -0
  29. data/lib/pwn/plugins/repl/ai_console_usage.rb +144 -0
  30. data/lib/pwn/plugins/repl/ai_swarm.rb +375 -0
  31. data/lib/pwn/plugins/repl.rb +25 -3
  32. data/lib/pwn/version.rb +1 -1
  33. data/spec/lib/pwn/ai/agent/loop_spec.rb +258 -1
  34. data/spec/lib/pwn/ai/agent/turn_finalizer_spec.rb +3 -2
  35. data/spec/lib/pwn/ai/open_ai_spec.rb +5 -0
  36. data/spec/lib/pwn/banner_spec.rb +643 -0
  37. data/spec/lib/pwn/blockchain/btc_spec.rb +372 -1
  38. data/spec/lib/pwn/blockchain/eth_spec.rb +205 -0
  39. data/spec/lib/pwn/blockchain_spec.rb +6 -0
  40. data/spec/lib/pwn/config_spec.rb +10 -0
  41. data/spec/lib/pwn/migrate_spec.rb +40 -3
  42. data/spec/lib/pwn/plugins/repl/ai_console_commands_spec.rb +65 -0
  43. data/spec/lib/pwn/plugins/repl/ai_console_spec.rb +1434 -0
  44. data/spec/lib/pwn/plugins/repl/ai_console_usage_spec.rb +29 -0
  45. data/spec/lib/pwn/plugins/repl/ai_swarm_spec.rb +127 -0
  46. data/spec/lib/pwn/plugins/repl_pwn_vault_spec.rb +5 -3
  47. data/spec/lib/pwn/plugins/repl_spec.rb +167 -1
  48. data/third_party/pwn_rdoc.jsonl +229 -10
  49. metadata +18 -6
  50. data/etc/default_skills/pwn/blockchain/btc/references/urls.md +0 -3
@@ -2,97 +2,378 @@
2
2
 
3
3
  require 'json'
4
4
  require 'rest-client'
5
+ require 'uri'
6
+ require 'openssl'
7
+ require 'timeout'
5
8
 
6
9
  module PWN
7
10
  module Blockchain
8
- # This plugin interacts with BitCoin's Blockchain API.
11
+ # Read-only Ethereum intelligence via BlockCypher and explicit JSON-RPC endpoints.
9
12
  module ETH
13
+ class RPCError < StandardError; end
14
+ TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
15
+
16
+ # Decode the standard Transfer event layout, not contract conformance.
10
17
  # Supported Method Parameters::
11
- # eth_rest_call(
12
- # http_method: 'optional HTTP method (defaults to GET)
13
- # rest_call: 'required rest call to make per the schema',
14
- # params: 'optional params passed in the URI or HTTP Headers',
15
- # http_body: 'optional HTTP body sent in HTTP methods that support it e.g. POST',
16
- # timeout: 'optional timeout in seconds (defaults to 180)',
17
- # spinner: 'optional - display spinner (defaults to false)'
18
+ # PWN::Blockchain::ETH.decode_transfer(
19
+ # log: 'required - symbol-keyed log with topics and data; unknown signatures return nil'
18
20
  # )
21
+ public_class_method def self.decode_transfer(opts = {})
22
+ log = opts[:log]
23
+ raise ArgumentError, 'log must be a hash with topics' unless log.is_a?(Hash) && log[:topics].is_a?(Array)
19
24
 
20
- private_class_method def self.eth_rest_call(opts = {})
21
- http_method = if opts[:http_method].nil?
22
- :get
23
- else
24
- opts[:http_method].to_s.scrub.to_sym
25
- end
26
-
27
- base_uri = 'https://api.blockcypher.com/v1/eth/'
28
- rest_call = opts[:rest_call].to_s.scrub
29
- params = opts[:params]
30
- headers = { content_type: 'application/json; charset=UTF-8' }
31
-
32
- http_body = opts[:http_body]
33
- http_body ||= {}
34
-
35
- timeout = opts[:timeout]
36
- timeout ||= 180
37
-
38
- spinner = opts[:spinner] || false
39
-
40
- browser_obj = PWN::Plugins::TransparentBrowser.open(browser_type: :rest)
41
- rest_client = browser_obj[:browser]::Request
42
-
43
- spin = PWN::Plugins::TTYSpinner.start if spinner
44
-
45
- retries = 0
46
- case http_method
47
- when :delete, :get
48
- headers[:params] = params
49
- response = rest_client.execute(
50
- method: http_method,
51
- url: "#{base_uri}#{rest_call}",
52
- headers: headers,
53
- verify_ssl: false,
54
- timeout: timeout
55
- )
25
+ topics = log[:topics]
26
+ raise ArgumentError, 'Too many event topics' if topics.length > 4
56
27
 
57
- when :post
58
- if http_body.key?(:multipart)
59
- headers[:content_type] = 'multipart/form-data'
60
-
61
- response = rest_client.execute(
62
- method: http_method,
63
- url: "#{base_uri}#{rest_call}",
64
- headers: headers,
65
- payload: http_body,
66
- verify_ssl: false,
67
- timeout: timeout
68
- )
69
- else
70
- response = rest_client.execute(
71
- method: http_method,
72
- url: "#{base_uri}#{rest_call}",
73
- headers: headers,
74
- payload: http_body.to_json,
75
- verify_ssl: false,
76
- timeout: timeout
77
- )
78
- end
28
+ topics.each { |topic| hex_identifier(value: topic, size: 32) }
29
+ return nil unless topics.first.is_a?(String) && topics.first.downcase == TRANSFER_TOPIC
79
30
 
31
+ raise ArgumentError, 'Invalid Transfer topic count' unless [3, 4].include?(topics.length)
32
+
33
+ raise ArgumentError, 'Noncanonical indexed address' unless topics[1..2].all? { |topic| topic.match?(/\A0x0{24}[0-9a-fA-F]{40}\z/) }
34
+
35
+ result = { standard: topics.length == 3 ? :erc20 : :erc721, conformance: :unverified,
36
+ from: "0x#{topics[1][-40..].downcase}", to: "0x#{topics[2][-40..].downcase}" }
37
+ if topics.length == 3
38
+ result[:value] = hex_identifier(value: log[:data], size: 32).to_i(16)
80
39
  else
81
- raise "Unsupported HTTP Method #{http_method} for #{self} Plugin"
40
+ raise ArgumentError, 'ERC721 Transfer data must be empty' unless log[:data] == '0x'
41
+
42
+ result[:token_id] = topics[3].to_i(16)
82
43
  end
44
+ result
45
+ end
46
+
47
+ private_class_method def self.numeric_range(opts = {})
48
+ first = opts[:from_block]
49
+ last = opts[:to_block]
50
+ raise ArgumentError, 'Range requires nonnegative integer from_block <= to_block' unless first.is_a?(Integer) && last.is_a?(Integer) && first >= 0 && last >= first
51
+
52
+ [first, last]
53
+ end
54
+
55
+ # Query bounded logs; provider truncation cannot be independently detected.
56
+ # Supported Method Parameters::
57
+ # PWN::Blockchain::ETH.event_logs(
58
+ # rpc_url: 'required - explicit Ethereum HTTP(S) JSON-RPC endpoint',
59
+ # from_block: 'required - nonnegative integer start height',
60
+ # to_block: 'required - integer inclusive end height; maximum span 1000 blocks',
61
+ # address: 'optional - 20-byte emitting contract address filter',
62
+ # topics: 'optional - up to four 32-byte topic filters or nil wildcards',
63
+ # limit: 'optional - returned log cap from 1 to 10000, default 1000',
64
+ # timeout: 'optional - request timeout in seconds from 1 to 120, default 30'
65
+ # )
66
+ public_class_method def self.event_logs(opts = {})
67
+ first, last = numeric_range(opts)
68
+ raise ArgumentError, 'Log range exceeds 1000 blocks' if last - first >= 1000
69
+
70
+ limit = opts.fetch(:limit, 1000)
71
+ raise ArgumentError, 'limit must be an integer from 1 to 10000' unless limit.is_a?(Integer) && limit.between?(1, 10_000)
83
72
 
84
- response
85
- rescue RestClient::ExceptionWithResponse => e
86
- case e.http_code
87
- when 400, 404
88
- "#{e.http_code} #{e.message}: #{e.response.body}"
73
+ filter = { fromBlock: block_tag(value: first), toBlock: block_tag(value: last) }
74
+ filter[:address] = hex_identifier(value: opts[:address], size: 20) if opts[:address]
75
+ topics = opts.fetch(:topics, [])
76
+ raise ArgumentError, 'topics must be an array of at most four topics' unless topics.is_a?(Array) && topics.length <= 4
77
+
78
+ filter[:topics] = topics.map { |topic| topic.nil? ? nil : hex_identifier(value: topic, size: 32) }
79
+ logs = rpc(opts.merge(method: 'eth_getLogs', params: [filter]))
80
+ raise RPCError, 'Invalid logs response' unless logs.is_a?(Array)
81
+
82
+ rows = logs.first(limit).map do |log|
83
+ raise RPCError, 'Invalid log object' unless log.is_a?(Hash)
84
+
85
+ hex_identifier(value: log[:address], size: 20)
86
+ hex_data(value: log[:data])
87
+ height = quantity(value: log[:blockNumber])
88
+ raise RPCError, 'Provider log outside requested range' unless height.between?(first, last)
89
+
90
+ hex_identifier(value: log[:transactionHash], size: 32)
91
+ log.merge(transfer: decode_transfer(log: log))
92
+ end
93
+ { source: :ethereum_json_rpc, from_block: first, to_block: last, logs: rows,
94
+ truncated: logs.length > limit, complete: false, provider_completeness: :unverified,
95
+ returned_count: rows.length, internal_traces: :not_covered }
96
+ end
97
+
98
+ # Scan top-level transactions in bounded whole-block pages, not internal calls or token events.
99
+ # Supported Method Parameters::
100
+ # PWN::Blockchain::ETH.address_activity(
101
+ # rpc_url: 'required - explicit Ethereum HTTP(S) JSON-RPC endpoint',
102
+ # address: 'required - 0x-prefixed 20-byte account address',
103
+ # from_block: 'required - nonnegative integer page start height',
104
+ # to_block: 'required - integer inclusive end height',
105
+ # page_size: 'optional - blocks to scan from 1 to 100, default 10; resume with next_block',
106
+ # timeout: 'optional - request timeout in seconds from 1 to 120, default 30'
107
+ # )
108
+ public_class_method def self.address_activity(opts = {})
109
+ address = hex_identifier(value: opts[:address], size: 20)
110
+ first, last = numeric_range(opts)
111
+ size = opts.fetch(:page_size, 10)
112
+ raise ArgumentError, 'page_size must be an integer from 1 to 100' unless size.is_a?(Integer) && size.between?(1, 100)
113
+
114
+ stop = [first + size - 1, last].min
115
+ blocks = []
116
+ transactions = []
117
+ (first..stop).each do |height|
118
+ data = block(opts.merge(block: height, full_transactions: true))[:block]
119
+ raise RPCError, 'Missing or inconsistent activity block' unless data && quantity(value: data[:number]) == height && data[:transactions].is_a?(Array)
120
+
121
+ hash = hex_identifier(value: data[:hash], size: 32)
122
+ blocks << { number: height, hash: hash }
123
+ data[:transactions].each do |tx|
124
+ raise RPCError, 'Expected full transaction object' unless tx.is_a?(Hash)
125
+
126
+ next unless [tx[:from], tx[:to]].compact.any? { |value| value.is_a?(String) && value.downcase == address }
127
+
128
+ transactions << tx.merge(block_number: height, block_hash: hash, value_wei: quantity(value: tx[:value]))
129
+ end
130
+ end
131
+ { source: :ethereum_json_rpc, address: address, transactions: transactions, blocks: blocks,
132
+ next_block: stop < last ? stop + 1 : nil, complete: stop == last,
133
+ coverage: :top_level_transactions_only, internal_traces: :not_covered,
134
+ token_events: :not_covered, reorg_safe: false, from_block: first, to_block: stop }
135
+ end
136
+
137
+ # Execute read-only eth_call at a pinned canonical block; no signing or submission.
138
+ # Supported Method Parameters::
139
+ # PWN::Blockchain::ETH.call(
140
+ # rpc_url: 'required - explicit Ethereum HTTP(S) JSON-RPC endpoint',
141
+ # contract: 'required - 0x-prefixed 20-byte contract address',
142
+ # data: 'required - ABI-encoded even-length 0x-prefixed calldata, maximum 128 KiB',
143
+ # block: 'optional - block number, hash or stable tag, default latest',
144
+ # timeout: 'optional - request timeout in seconds from 1 to 120, default 30'
145
+ # )
146
+ public_class_method def self.call(opts = {})
147
+ address = hex_identifier(value: opts[:contract], size: 20)
148
+ data = hex_data(value: opts[:data])
149
+ raise ArgumentError, 'Calldata exceeds 128 KiB' if data.length > 262_146
150
+
151
+ context = snapshot(opts)
152
+ params = [{ to: address, data: data }, { blockHash: context[:block_hash], requireCanonical: true }]
153
+ result = hex_data(value: rpc(opts.merge(method: 'eth_call', params: params)))
154
+ context.merge(source: :ethereum_json_rpc, contract: address, data: result)
155
+ end
156
+
157
+ # Read optional token metadata; layouts do not prove ERC conformance, and RPC failures propagate.
158
+ # Supported Method Parameters::
159
+ # PWN::Blockchain::ETH.token_metadata(
160
+ # rpc_url: 'required - explicit Ethereum HTTP(S) JSON-RPC endpoint supporting EIP-1898',
161
+ # contract: 'required - 0x-prefixed 20-byte token contract address',
162
+ # block: 'optional - integer, hash or stable tag for pinned reads, default latest',
163
+ # timeout: 'optional - request timeout from 1 to 120 seconds, default 30'
164
+ # )
165
+ public_class_method def self.token_metadata(opts = {})
166
+ contract = hex_identifier(value: opts[:contract], size: 20)
167
+ context = snapshot(opts)
168
+ result = context.merge(source: :ethereum_json_rpc, contract: contract, conformance: :unverified, unavailable: [])
169
+ { name: '0x06fdde03', symbol: '0x95d89b41', decimals: '0x313ce567', total_supply: '0x18160ddd' }.each do |field, selector|
170
+ params = [{ to: contract, data: selector }, { blockHash: context[:block_hash], requireCanonical: true }]
171
+ raw = hex_data(value: rpc(opts.merge(method: 'eth_call', params: params)))
172
+ value = if %i[name symbol].include?(field)
173
+ abi_string(value: raw)
174
+ elsif raw.match?(/\A0x[0-9a-fA-F]{64}\z/)
175
+ raw.to_i(16)
176
+ end
177
+ value = nil if field == :decimals && value && value > 255
178
+ result[field] = value
179
+ result[:unavailable] << field if value.nil?
180
+ end
181
+ result
182
+ end
183
+
184
+ private_class_method def self.abi_string(opts = {})
185
+ hex = opts[:value][2..]
186
+ return nil if hex.empty? || hex.length > 16_384
187
+
188
+ if hex.length == 64
189
+ bytes = [hex].pack('H*').sub(/\x00+\z/, '')
89
190
  else
90
- raise e
191
+ return nil unless hex.length >= 128 && hex[0, 64].to_i(16) == 32
192
+
193
+ length = hex[64, 64].to_i(16)
194
+ padded = ((length + 31) / 32) * 64
195
+ return nil unless length <= 4096 && hex.length == 128 + padded
196
+ return nil unless hex[(128 + (length * 2))..].match?(/\A0*\z/)
197
+
198
+ bytes = [hex[128, length * 2]].pack('H*')
199
+ end
200
+ bytes.force_encoding(Encoding::UTF_8)
201
+ bytes.valid_encoding? ? bytes : nil
202
+ end
203
+
204
+ private_class_method def self.hex_identifier(opts = {})
205
+ value = opts[:value]
206
+ size = opts[:size]
207
+ raise ArgumentError, "Expected 0x-prefixed #{size}-byte identifier" unless value.is_a?(String) && value.match?(/\A0x[0-9a-fA-F]{#{size * 2}}\z/)
208
+
209
+ value.downcase
210
+ end
211
+
212
+ private_class_method def self.block_tag(opts = {})
213
+ value = opts[:value]
214
+ return "0x#{value.to_s(16)}" if value.is_a?(Integer) && value >= 0
215
+ return value if value.is_a?(String) && (value.match?(/\A0x(?:0|[1-9a-fA-F][0-9a-fA-F]*)\z/) || %w[latest earliest pending safe finalized].include?(value))
216
+
217
+ raise ArgumentError, 'Invalid block number or tag'
218
+ end
219
+
220
+ private_class_method def self.hex_data(opts = {})
221
+ value = opts[:value]
222
+ raise RPCError, 'Invalid hex data' unless value.is_a?(String) && value.match?(/\A0x(?:[0-9a-fA-F]{2})*\z/)
223
+
224
+ value
225
+ end
226
+
227
+ # Read a block by number, tag or hash; raw quantities remain exact hex.
228
+ # Supported Method Parameters::
229
+ # PWN::Blockchain::ETH.block(
230
+ # rpc_url: 'required - explicit Ethereum HTTP(S) JSON-RPC endpoint',
231
+ # block: 'optional - nonnegative integer, canonical hex quantity, tag or 32-byte hash; default latest',
232
+ # full_transactions: 'optional - boolean to return transaction objects, default false',
233
+ # timeout: 'optional - request timeout in seconds from 1 to 120, default 30'
234
+ # )
235
+ public_class_method def self.block(opts = {})
236
+ selector = opts.key?(:block) ? opts[:block] : 'latest'
237
+ full = opts.fetch(:full_transactions, false)
238
+ raise ArgumentError, 'full_transactions must be boolean' unless [true, false].include?(full)
239
+
240
+ by_hash = selector.is_a?(String) && selector.match?(/\A0x[0-9a-fA-F]{64}\z/)
241
+ selector = by_hash ? hex_identifier(value: selector, size: 32) : block_tag(value: selector)
242
+ result = rpc(opts.merge(method: by_hash ? 'eth_getBlockByHash' : 'eth_getBlockByNumber', params: [selector, full]))
243
+ raise RPCError, 'Invalid block response' unless result.nil? || result.is_a?(Hash)
244
+
245
+ if result && selector != 'pending'
246
+ hash = hex_identifier(value: result[:hash], size: 32)
247
+ number = quantity(value: result[:number])
248
+ raise RPCError, 'Block hash does not match request' if by_hash && hash != selector
249
+ raise RPCError, 'Block height does not match request' if !by_hash && selector.start_with?('0x') && number != quantity(value: selector)
91
250
  end
92
- rescue StandardError => e
93
- raise e
94
- ensure
95
- PWN::Plugins::TTYSpinner.stop(spin: spin)
251
+ { source: :ethereum_json_rpc, requested_block: selector, block: result }
252
+ end
253
+
254
+ private_class_method def self.snapshot(opts = {})
255
+ raise ArgumentError, 'Pending block cannot pin state' if opts[:block] == 'pending'
256
+
257
+ result = block(opts)[:block]
258
+ raise RPCError, 'Block not found or pending; stable block required' unless result && result[:number] && result[:hash]
259
+
260
+ { block_number: quantity(value: result[:number]), block_hash: hex_identifier(value: result[:hash], size: 32) }
261
+ end
262
+
263
+ # Inspect balance, nonce and bytecode at one pinned block hash.
264
+ # Supported Method Parameters::
265
+ # PWN::Blockchain::ETH.account(
266
+ # rpc_url: 'required - explicit Ethereum HTTP(S) JSON-RPC endpoint',
267
+ # address: 'required - 0x-prefixed 20-byte account address',
268
+ # block: 'optional - block number, hash or stable tag, default latest',
269
+ # timeout: 'optional - request timeout in seconds from 1 to 120, default 30'
270
+ # )
271
+ public_class_method def self.account(opts = {})
272
+ address = hex_identifier(value: opts[:address], size: 20)
273
+ context = snapshot(opts)
274
+ params = [address, { blockHash: context[:block_hash], requireCanonical: true }]
275
+ context.merge(source: :ethereum_json_rpc, address: address,
276
+ balance_wei: quantity(value: rpc(opts.merge(method: 'eth_getBalance', params: params))),
277
+ nonce: quantity(value: rpc(opts.merge(method: 'eth_getTransactionCount', params: params))),
278
+ code: hex_data(value: rpc(opts.merge(method: 'eth_getCode', params: params))))
279
+ end
280
+
281
+ # Inspect transaction and receipt; fees exclude chain-specific L2 surcharges.
282
+ # Supported Method Parameters::
283
+ # PWN::Blockchain::ETH.transaction(
284
+ # rpc_url: 'required - explicit Ethereum HTTP(S) JSON-RPC endpoint',
285
+ # hash: 'required - 0x-prefixed 32-byte transaction hash',
286
+ # timeout: 'optional - request timeout in seconds from 1 to 120, default 30'
287
+ # )
288
+ public_class_method def self.transaction(opts = {})
289
+ hash = hex_identifier(value: opts[:hash], size: 32)
290
+ tx = rpc(opts.merge(method: 'eth_getTransactionByHash', params: [hash]))
291
+ result = { source: :ethereum_json_rpc, hash: hash, internal_traces: :not_covered }
292
+ return result.merge(status: :not_found) if tx.nil?
293
+
294
+ raise RPCError, 'Invalid transaction response' unless tx.is_a?(Hash) && tx[:hash]&.downcase == hash
295
+
296
+ receipt = rpc(opts.merge(method: 'eth_getTransactionReceipt', params: [hash]))
297
+ result.merge!(transaction: tx, receipt: receipt, value_wei: quantity(value: tx[:value]), block_number: tx[:blockNumber] && quantity(value: tx[:blockNumber]))
298
+ return result.merge(status: tx[:blockNumber] ? :receipt_unavailable : :pending) unless receipt
299
+
300
+ raise RPCError, 'Invalid receipt response' unless receipt.is_a?(Hash) && receipt[:transactionHash]&.downcase == hash
301
+
302
+ raise RPCError, 'Transaction and receipt inclusion heights differ' if receipt[:blockNumber] && receipt[:blockNumber] != tx[:blockNumber]
303
+ raise RPCError, 'Transaction and receipt block hashes differ' if receipt[:blockHash] && tx[:blockHash] && receipt[:blockHash].downcase != tx[:blockHash].downcase
304
+
305
+ status = receipt[:status] && quantity(value: receipt[:status])
306
+ raise RPCError, 'Invalid receipt status' unless [nil, 0, 1].include?(status)
307
+
308
+ gas_price = receipt[:effectiveGasPrice] || tx[:gasPrice]
309
+ fee = gas_price && (quantity(value: receipt[:gasUsed]) * quantity(value: gas_price))
310
+ blob_fee = (quantity(value: receipt[:blobGasUsed]) * quantity(value: receipt[:blobGasPrice]) if receipt[:blobGasUsed] && receipt[:blobGasPrice])
311
+ result.merge(status: { 0 => :reverted, 1 => :success }.fetch(status, :unknown),
312
+ block_hash: receipt[:blockHash], execution_fee_wei: fee, blob_fee_wei: blob_fee,
313
+ fee_scope: :execution_and_blob_only, contract_creation: tx[:to].nil?, contract_address: receipt[:contractAddress])
314
+ end
315
+
316
+ private_class_method def self.quantity(opts = {})
317
+ value = opts[:value]
318
+ raise RPCError, 'Invalid RPC quantity' unless value.is_a?(String) && value.match?(/\A0x(?:0|[1-9a-fA-F][0-9a-fA-F]*)\z/)
319
+
320
+ value.to_i(16)
321
+ end
322
+
323
+ private_class_method def self.rpc(opts = {})
324
+ uri = URI.parse(opts[:rpc_url].to_s)
325
+ raise ArgumentError, 'rpc_url must be an explicit HTTP(S) endpoint without userinfo or fragment' unless %w[http https].include?(uri.scheme) && uri.host && !uri.userinfo && !uri.fragment
326
+
327
+ timeout = opts.fetch(:timeout, 30)
328
+ raise ArgumentError, 'timeout must be an integer from 1 to 120' unless timeout.is_a?(Integer) && timeout.between?(1, 120)
329
+
330
+ response = RestClient::Request.execute(
331
+ method: :post, url: uri.to_s,
332
+ headers: { content_type: :json, accept: :json },
333
+ payload: JSON.generate(jsonrpc: '2.0', id: 1, method: opts[:method], params: opts.fetch(:params, [])),
334
+ verify_ssl: OpenSSL::SSL::VERIFY_PEER, open_timeout: 10, timeout: timeout,
335
+ max_redirects: 0
336
+ )
337
+ body = JSON.parse(response.body, symbolize_names: true)
338
+ raise RPCError, 'Invalid JSON-RPC envelope' unless body.is_a?(Hash) && body[:jsonrpc] == '2.0' && body[:id] == 1
339
+ raise RPCError, 'JSON-RPC provider returned an error' if body.key?(:error)
340
+ raise RPCError, 'Missing JSON-RPC result' unless body.key?(:result)
341
+
342
+ body[:result]
343
+ rescue URI::InvalidURIError
344
+ raise ArgumentError, 'Invalid rpc_url', cause: nil
345
+ rescue RestClient::Exception, OpenSSL::SSL::SSLError, IOError, SystemCallError, SocketError, Timeout::Error
346
+ raise RPCError, 'Ethereum HTTP transport failed', cause: nil
347
+ rescue JSON::ParserError
348
+ raise RPCError, 'Invalid JSON-RPC JSON response', cause: nil
349
+ end
350
+
351
+ # Read the endpoint chain identity, head height and sync state.
352
+ # Supported Method Parameters::
353
+ # PWN::Blockchain::ETH.chain_status(
354
+ # rpc_url: 'required - explicit Ethereum HTTP(S) JSON-RPC endpoint',
355
+ # timeout: 'optional - request timeout in seconds from 1 to 120, default 30'
356
+ # )
357
+ public_class_method def self.chain_status(opts = {})
358
+ rpc_url = opts[:rpc_url]
359
+ context = opts.merge(rpc_url: rpc_url)
360
+ {
361
+ source: :ethereum_json_rpc,
362
+ chain_id: quantity(value: rpc(context.merge(method: 'eth_chainId'))),
363
+ block_number: quantity(value: rpc(context.merge(method: 'eth_blockNumber'))),
364
+ syncing: rpc(context.merge(method: 'eth_syncing'))
365
+ }
366
+ end
367
+
368
+ # Internal read-only BlockCypher transport.
369
+ private_class_method def self.eth_rest_call(opts = {})
370
+ RestClient::Request.execute(
371
+ method: :get, url: "https://api.blockcypher.com/v1/eth/#{opts[:rest_call]}",
372
+ headers: { content_type: :json, params: opts[:params] },
373
+ verify_ssl: OpenSSL::SSL::VERIFY_PEER, timeout: 30, open_timeout: 10, max_redirects: 0
374
+ )
375
+ rescue RestClient::Exception, OpenSSL::SSL::SSLError, IOError, SystemCallError, SocketError, Timeout::Error
376
+ raise RPCError, 'BlockCypher HTTP transport failed', cause: nil
96
377
  end
97
378
 
98
379
  # Supported Method Parameters::
@@ -108,8 +389,8 @@ module PWN
108
389
  response = eth_rest_call(rest_call: rest_call, params: params)
109
390
 
110
391
  JSON.parse(response.body, symbolize_names: true)
111
- rescue StandardError => e
112
- raise e
392
+ rescue JSON::ParserError
393
+ raise RPCError, 'Invalid BlockCypher JSON response', cause: nil
113
394
  end
114
395
 
115
396
  # Supported Method Parameters::
@@ -119,6 +400,8 @@ module PWN
119
400
  # )
120
401
  public_class_method def self.get_block_details(opts = {})
121
402
  height = opts[:height]
403
+ raise ArgumentError, 'height must be a nonnegative integer or decimal string' unless (height.is_a?(Integer) && height >= 0) || (height.is_a?(String) && height.match?(/\A(?:0|[1-9][0-9]*)\z/))
404
+
122
405
  params = {}
123
406
  params[:token] = opts[:token] if opts[:token]
124
407
 
@@ -126,8 +409,8 @@ module PWN
126
409
  response = eth_rest_call(rest_call: rest_call, params: params)
127
410
 
128
411
  JSON.parse(response.body, symbolize_names: true)
129
- rescue StandardError => e
130
- raise e
412
+ rescue JSON::ParserError
413
+ raise RPCError, 'Invalid BlockCypher JSON response', cause: nil
131
414
  end
132
415
 
133
416
  # Author(s):: 0day Inc. <support@0dayinc.com>
@@ -142,6 +425,82 @@ module PWN
142
425
 
143
426
  public_class_method def self.help
144
427
  puts "USAGE:
428
+ # Read endpoint chain identity, height and synchronization state.
429
+ #{self}.chain_status(
430
+ rpc_url: 'required - explicit HTTP(S) JSON-RPC endpoint; never persisted',
431
+ timeout: 'optional - request timeout from 1 to 120 seconds, default 30'
432
+ )
433
+
434
+ # Read a block with raw exact hex quantities.
435
+ #{self}.block(
436
+ rpc_url: 'required - explicit HTTP(S) JSON-RPC endpoint',
437
+ block: 'optional - integer, canonical hex quantity, tag or 32-byte hash; default latest',
438
+ full_transactions: 'optional - boolean transaction object expansion, default false',
439
+ timeout: 'optional - request timeout from 1 to 120 seconds, default 30'
440
+ )
441
+
442
+ # Inspect receipt status and exact execution/blob fees, excluding L2 surcharges.
443
+ #{self}.transaction(
444
+ rpc_url: 'required - explicit HTTP(S) JSON-RPC endpoint',
445
+ hash: 'required - 0x-prefixed 32-byte transaction hash',
446
+ timeout: 'optional - request timeout from 1 to 120 seconds, default 30'
447
+ )
448
+
449
+ # Inspect balance, nonce and code using EIP-1898 pinned canonical block reads.
450
+ #{self}.account(
451
+ rpc_url: 'required - explicit HTTP(S) JSON-RPC endpoint supporting EIP-1898',
452
+ address: 'required - 0x-prefixed 20-byte account address',
453
+ block: 'optional - integer, canonical hex, hash or stable tag; default latest',
454
+ timeout: 'optional - request timeout from 1 to 120 seconds, default 30'
455
+ )
456
+
457
+ # Query bounded event logs; silent provider truncation remains unverified.
458
+ #{self}.event_logs(
459
+ rpc_url: 'required - explicit HTTP(S) JSON-RPC endpoint',
460
+ from_block: 'required - nonnegative integer start height',
461
+ to_block: 'required - inclusive integer end height; maximum 1000 blocks',
462
+ address: 'optional - 0x-prefixed 20-byte emitting contract address',
463
+ topics: 'optional - array of at most four 32-byte topics or nil wildcards',
464
+ limit: 'optional - result cap from 1 to 10000, default 1000; truncation is explicit',
465
+ timeout: 'optional - request timeout from 1 to 120 seconds, default 30'
466
+ )
467
+
468
+ # Decode standard ERC20/ERC721 Transfer layouts, not ERC1155 or proven conformance.
469
+ #{self}.decode_transfer(
470
+ log: 'required - symbol-keyed log with topics and data; unknown signatures return nil'
471
+ )
472
+
473
+ # Scan whole-block pages of top-level transactions; no token events or internal traces.
474
+ #{self}.address_activity(
475
+ rpc_url: 'required - explicit HTTP(S) JSON-RPC endpoint',
476
+ address: 'required - 0x-prefixed 20-byte account address',
477
+ from_block: 'required - nonnegative integer page start; resume with next_block',
478
+ to_block: 'required - inclusive integer end height',
479
+ page_size: 'optional - blocks per page from 1 to 100, default 10',
480
+ timeout: 'optional - request timeout from 1 to 120 seconds, default 30'
481
+ )
482
+
483
+ # Execute ABI-encoded read-only eth_call at a pinned block, never send or sign.
484
+ #{self}.call(
485
+ rpc_url: 'required - explicit HTTP(S) JSON-RPC endpoint supporting EIP-1898',
486
+ contract: 'required - 0x-prefixed 20-byte contract address',
487
+ data: 'required - even-length 0x-prefixed ABI calldata, maximum 128 KiB',
488
+ block: 'optional - integer, canonical hex, hash or stable tag; default latest',
489
+ timeout: 'optional - request timeout from 1 to 120 seconds, default 30'
490
+ )
491
+
492
+ # Read token metadata at one block; empty/malformed ABI fields are unavailable, RPC errors propagate.
493
+ #{self}.token_metadata(
494
+ rpc_url: 'required - explicit HTTP(S) JSON-RPC endpoint supporting EIP-1898',
495
+ contract: 'required - 0x-prefixed 20-byte token contract address',
496
+ block: 'optional - integer, canonical hex, hash or stable tag; default latest',
497
+ timeout: 'optional - request timeout from 1 to 120 seconds, default 30'
498
+ )
499
+
500
+ # Coverage excludes internal traces. Activity completeness is only for the requested
501
+ # top-level range; block pages can reorganize. Use finalized ranges where possible.
502
+ # RPC errors are redacted. No implicit endpoint, keys, signing or wallet changes.
503
+
145
504
  # Run get latest block and return its result
146
505
  #{self}.get_latest_block(
147
506
  token: 'optional - API token for higher rate limits'
@@ -18,6 +18,12 @@ module PWN
18
18
 
19
19
  public_class_method def self.help
20
20
  puts "USAGE:
21
+ # Read-only Bitcoin Core intelligence: transactions, UTXOs, bounded ancestor traces and scans.
22
+ PWN::Blockchain::BTC.help
23
+
24
+ # Read-only Ethereum intelligence: receipts, pinned account state, contract reads and event logs.
25
+ PWN::Blockchain::ETH.help
26
+
21
27
  # Display a List of Every PWN::Blockchain Module
22
28
  #{self}.authors
23
29
  "
data/lib/pwn/config.rb CHANGED
@@ -154,6 +154,28 @@ module PWN
154
154
  reflect_engine: nil,
155
155
  # optional model override on :reflect_engine (nil = engine default)
156
156
  reflect_model: nil,
157
+ tui: {
158
+ theme: {
159
+ border: 'black',
160
+ title: 'red',
161
+ operator: 'red',
162
+ request: 'white',
163
+ assistant: 'white',
164
+ task: 'green',
165
+ tool: 'cyan',
166
+ result: 'yellow',
167
+ notice: 'cyan',
168
+ warning: 'red',
169
+ category: 'yellow',
170
+ value: 'white',
171
+ composer: 'white',
172
+ header: 'white',
173
+ footer: 'white',
174
+ prompt: 'red',
175
+ selection: 'red',
176
+ status: 'yellow'
177
+ }
178
+ },
157
179
  agent: {
158
180
  native_tools: true,
159
181
  max_iters: 777,
data/lib/pwn/migrate.rb CHANGED
@@ -49,7 +49,7 @@ module PWN
49
49
  # Bump this whenever the shape of any file under ~/.pwn changes in a
50
50
  # way that requires a one-time transform. Add the transform as an
51
51
  # entry in MIGRATIONS keyed by the NEW schema number.
52
- SCHEMA_VERSION = 5
52
+ SCHEMA_VERSION = 7
53
53
 
54
54
  OK = "\e[32mok\e[0m"
55
55
  BAD = "\e[31mFAIL\e[0m"
@@ -249,6 +249,14 @@ module PWN
249
249
  5 => lambda { |_root, io|
250
250
  io.puts ' · pwn.yaml ai.agent.skill_review'
251
251
  PWN::Migrate.backfill_vault(io: io)
252
+ },
253
+ 6 => lambda { |_root, io|
254
+ io.puts ' · pwn.yaml ai.tui.theme'
255
+ PWN::Migrate.backfill_vault(io: io)
256
+ },
257
+ 7 => lambda { |_root, io|
258
+ io.puts ' · pwn.yaml ai.tui.theme.title'
259
+ PWN::Migrate.backfill_vault(io: io)
252
260
  }
253
261
  }.freeze
254
262