Class: BSV::Wallet::Engine
- Inherits:
-
Object
- Object
- BSV::Wallet::Engine
- Includes:
- Interface::BRC100
- Defined in:
- lib/bsv/wallet/engine.rb
Overview
Layer 3 — BRC-100 business process orchestration.
Receives Layer 2a components at construction time and orchestrates them to fulfill the 28 BRC-100 methods. Contains no SQL, no ARC calls, no thread management. Pure orchestration.
Constant Summary collapse
- ACCEPTED_STATUSES =
%w[SEEN_ON_NETWORK MINED ACCEPTED_BY_NETWORK IMMUTABLE].freeze
- UUID_RE =
/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i- LIMP_THRESHOLD =
default: 50K sats
50_000- LIMP_THRESHOLD_MIN =
hard floor: cannot configure below this
10_000
Instance Attribute Summary collapse
-
#limp_threshold ⇒ Object
readonly
Returns the value of attribute limp_threshold.
Instance Method Summary collapse
- #abort_action(reference:, originator: nil) ⇒ Object
-
#acquire_certificate(type:, certifier:, acquisition_protocol:, fields:, serial_number: nil, revocation_outpoint: nil, signature: nil, certifier_url: nil, keyring_revealer: nil, keyring_for_subject: nil, privileged: false, privileged_reason: nil, originator: nil) ⇒ Object
— Identity and Certificate Management (codes 17-22) —.
-
#authenticated?(originator: nil) ⇒ Boolean
— Authentication (codes 23-24) —.
-
#create_action(description:, input_beef: nil, inputs: nil, outputs: nil, lock_time: nil, version: nil, labels: nil, sign_and_process: true, accept_delayed_broadcast: true, trust_self: nil, known_txids: nil, return_txid_only: false, no_send: false, no_send_change: nil, send_with: nil, randomize_outputs: true, originator: nil) ⇒ Object
— Transaction Operations (codes 1-7) —.
- #create_hmac(data:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) ⇒ Object
- #create_signature(protocol_id:, key_id:, data: nil, hash_to_directly_sign: nil, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) ⇒ Object
- #decrypt(ciphertext:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) ⇒ Object
- #discover_by_attributes(attributes:, limit: 10, offset: 0, seek_permission: true, originator: nil) ⇒ Object
- #discover_by_identity_key(identity_key:, limit: 10, offset: 0, seek_permission: true, originator: nil) ⇒ Object
-
#encrypt(plaintext:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) ⇒ Object
— Cryptography Operations (codes 11-16) —.
- #get_header_for_height(height:, originator: nil) ⇒ Object
-
#get_height(originator: nil) ⇒ Object
— Blockchain and Network Data (codes 25-28) —.
- #get_network(originator: nil) ⇒ Object
-
#get_public_key(identity_key: false, protocol_id: nil, key_id: nil, privileged: false, privileged_reason: nil, counterparty: nil, for_self: false, seek_permission: true, originator: nil) ⇒ Object
— Public Key Management (codes 8-10) —.
- #get_version(originator: nil) ⇒ Object
-
#headroom ⇒ Object
How many sats can be spent before hitting the limp threshold.
-
#import_utxo(dtxid:, vout: 0) ⇒ Hash
Import a root-key UTXO and immediately pay to self on a derived address.
-
#import_wallet ⇒ Hash
Scan the root key’s address for unspent outputs and import each one.
-
#initialize(store:, utxo_pool:, broadcast_queue:, proof_store:, key_deriver: nil, chain_tracker: nil, network_provider: nil, network: :mainnet, limp_threshold: LIMP_THRESHOLD) ⇒ Engine
constructor
A new instance of Engine.
- #internalize_action(tx:, outputs:, description:, labels: nil, trust_self: nil, known_txids: nil, seek_permission: true, originator: nil) ⇒ Object
-
#limp_mode? ⇒ Boolean
Is the wallet in limp mode? When true, all outbound operations are blocked.
- #list_actions(labels:, label_query_mode: :any, include_labels: false, include_inputs: false, include_input_source_locking_scripts: false, include_input_unlocking_scripts: false, include_outputs: false, include_output_locking_scripts: false, limit: 10, offset: 0, seek_permission: true, originator: nil) ⇒ Object
- #list_certificates(certifiers:, types:, limit: 10, offset: 0, privileged: false, privileged_reason: nil, originator: nil) ⇒ Object
- #list_outputs(basket:, tags: nil, tag_query_mode: :any, include: nil, include_custom_instructions: false, include_tags: false, include_labels: false, limit: 10, offset: 0, seek_permission: true, originator: nil) ⇒ Object
- #prove_certificate(certificate:, fields_to_reveal:, verifier:, privileged: false, privileged_reason: nil, originator: nil) ⇒ Object
- #relinquish_certificate(type:, serial_number:, certifier:, originator: nil) ⇒ Object
- #relinquish_output(basket:, output:, originator: nil) ⇒ Object
- #reveal_counterparty_key_linkage(counterparty:, verifier:, privileged: false, privileged_reason: nil, originator: nil) ⇒ Object
- #reveal_specific_key_linkage(counterparty:, verifier:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, originator: nil) ⇒ Object
-
#send_payment(recipient:, satoshis:) ⇒ Hash
Send a BRC-42 derived payment to a recipient.
- #sign_action(spends:, reference:, accept_delayed_broadcast: true, return_txid_only: false, no_send: false, send_with: nil, originator: nil) ⇒ Object
- #verify_hmac(data:, hmac:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) ⇒ Object
- #verify_signature(signature:, protocol_id:, key_id:, data: nil, hash_to_directly_verify: nil, privileged: false, privileged_reason: nil, counterparty: nil, for_self: false, seek_permission: true, originator: nil) ⇒ Object
- #wait_for_authentication(originator: nil) ⇒ Object
Constructor Details
#initialize(store:, utxo_pool:, broadcast_queue:, proof_store:, key_deriver: nil, chain_tracker: nil, network_provider: nil, network: :mainnet, limp_threshold: LIMP_THRESHOLD) ⇒ Engine
Returns a new instance of Engine.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/bsv/wallet/engine.rb', line 33 def initialize(store:, utxo_pool:, broadcast_queue:, proof_store:, key_deriver: nil, chain_tracker: nil, network_provider: nil, network: :mainnet, limp_threshold: LIMP_THRESHOLD) raise ArgumentError, "limp_threshold must be >= #{LIMP_THRESHOLD_MIN}" if limp_threshold < LIMP_THRESHOLD_MIN @store = store @utxo_pool = utxo_pool @broadcast_queue = broadcast_queue @proof_store = proof_store @key_deriver = key_deriver @chain_tracker = chain_tracker @network_provider = network_provider @network_name = network @limp_threshold = limp_threshold end |
Instance Attribute Details
#limp_threshold ⇒ Object (readonly)
Returns the value of attribute limp_threshold.
31 32 33 |
# File 'lib/bsv/wallet/engine.rb', line 31 def limp_threshold @limp_threshold end |
Instance Method Details
#abort_action(reference:, originator: nil) ⇒ Object
207 208 209 210 211 212 213 214 215 |
# File 'lib/bsv/wallet/engine.rb', line 207 def abort_action(reference:, originator: nil) validate_reference!(reference) action = @store.find_action(reference: reference) raise BSV::Wallet::InvalidParameterError, 'reference' unless action @store.abort_action(action_id: action[:id]) @utxo_pool.release(outputs: []) { aborted: true } end |
#acquire_certificate(type:, certifier:, acquisition_protocol:, fields:, serial_number: nil, revocation_outpoint: nil, signature: nil, certifier_url: nil, keyring_revealer: nil, keyring_for_subject: nil, privileged: false, privileged_reason: nil, originator: nil) ⇒ Object
— Identity and Certificate Management (codes 17-22) —
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 |
# File 'lib/bsv/wallet/engine.rb', line 640 def acquire_certificate(type:, certifier:, acquisition_protocol:, fields:, serial_number: nil, revocation_outpoint: nil, signature: nil, certifier_url: nil, keyring_revealer: nil, keyring_for_subject: nil, privileged: false, privileged_reason: nil, originator: nil) case acquisition_protocol when :direct, 'direct' @store.save_certificate( type: type, certifier: certifier, fields: fields, serial_number: serial_number, revocation_outpoint: revocation_outpoint, signature: signature, subject: @key_deriver&.identity_key, keyring: keyring_for_subject ) when :issuance, 'issuance' raise BSV::Wallet::UnsupportedActionError, 'certificate issuance protocol' else raise BSV::Wallet::InvalidParameterError.new('acquisition_protocol', 'either :direct or :issuance') end end |
#authenticated?(originator: nil) ⇒ Boolean
— Authentication (codes 23-24) —
709 710 711 |
# File 'lib/bsv/wallet/engine.rb', line 709 def authenticated?(originator: nil) { authenticated: !@key_deriver.nil? } end |
#create_action(description:, input_beef: nil, inputs: nil, outputs: nil, lock_time: nil, version: nil, labels: nil, sign_and_process: true, accept_delayed_broadcast: true, trust_self: nil, known_txids: nil, return_txid_only: false, no_send: false, no_send_change: nil, send_with: nil, randomize_outputs: true, originator: nil) ⇒ Object
— Transaction Operations (codes 1-7) —
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/bsv/wallet/engine.rb', line 62 def create_action(description:, input_beef: nil, inputs: nil, outputs: nil, lock_time: nil, version: nil, labels: nil, sign_and_process: true, accept_delayed_broadcast: true, trust_self: nil, known_txids: nil, return_txid_only: false, no_send: false, no_send_change: nil, send_with: nil, randomize_outputs: true, originator: nil) validate_description!(description) validate_create_action_params!(inputs: inputs, outputs: outputs) validate_output_ownership!(outputs) # Auto-fund: when inputs is nil with outputs present, the wallet # handles UTXO selection, fee estimation, and change generation. if inputs.nil? && outputs&.any? unless sign_and_process raise BSV::Wallet::InvalidParameterError.new( 'sign_and_process', 'true when inputs is nil (auto-funded actions sign immediately)' ) end require_key_deriver! enforce_limp_mode! return auto_fund_action( description: description, outputs: outputs, lock_time: lock_time, version: version, broadcast: determine_broadcast(no_send, accept_delayed_broadcast), labels: labels, randomize_outputs: randomize_outputs, no_send: no_send, send_with: send_with, return_txid_only: return_txid_only ) end broadcast = determine_broadcast(no_send, accept_delayed_broadcast) enforce_limp_mode! # Phase 1: Lock input_specs = build_input_specs(inputs) action_result = @store.create_action( action: { description: description, broadcast: broadcast, nlocktime: lock_time || 0, version: version, input_beef: input_beef, outgoing: true }, inputs: input_specs ) raise BSV::Wallet::InsufficientFundsError if action_result.nil? attach_labels(action_result[:id], labels) # Check for deferred signing deferred = !sign_and_process || inputs&.any? { |i| i[:unlocking_script_length] && !i[:unlocking_script] } # Phase 2: Build transaction (sign unless deferred) wtxid, raw_tx, vout_mapping = build_transaction( action_result[:id], inputs, outputs, lock_time, version, randomize_outputs, sign: !deferred ) if deferred # Store unsigned raw_tx (empty unlocking scripts) and promote outputs now. # Outputs are fully known at createAction time — the deferral is about # inputs (waiting for caller-provided unlocking scripts), not outputs. @store.sign_action(action_id: action_result[:id], wtxid: wtxid, raw_tx: raw_tx) @proof_store.save_proof(wtxid: wtxid, proof: { raw_tx: raw_tx }) promote_with_outputs(action_result[:id], outputs, vout_mapping) return { signable_transaction: { tx: nil, reference: action_result[:reference] } } end @store.sign_action(action_id: action_result[:id], wtxid: wtxid, raw_tx: raw_tx) @proof_store.save_proof(wtxid: wtxid, proof: { raw_tx: raw_tx }) BSV.logger&.debug { "[Engine] create_action: dtxid=#{wtxid.reverse.unpack1('H*')} outputs=#{outputs&.length || 0}" } # Build Atomic BEEF envelope for the :tx return value atomic_beef = build_atomic_beef(raw_tx, action_result[:id]) # No-send path: promote immediately, return change outpoints if no_send promote_with_outputs(action_result[:id], outputs, vout_mapping) change = query_change_outpoints(action_result[:id]) result = { txid: wtxid, tx: atomic_beef, no_send_change: change } result[:send_with_results] = process_send_with(send_with) if send_with&.any? return result end # Phase 3: Broadcast broadcast_result = @broadcast_queue.submit( action_id: action_result[:id], raw_tx: raw_tx, immediate: broadcast == :inline ) # Phase 4: Promote (if inline broadcast accepted) if broadcast == :inline && accepted?(broadcast_result) promote_with_outputs(action_result[:id], outputs, vout_mapping) handle_proof_from_broadcast(action_result[:id], broadcast_result) end result = { txid: wtxid, tx: return_txid_only ? nil : atomic_beef } result[:send_with_results] = process_send_with(send_with) if send_with&.any? result end |
#create_hmac(data:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) ⇒ Object
584 585 586 587 588 589 590 591 592 593 |
# File 'lib/bsv/wallet/engine.rb', line 584 def create_hmac(data:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) require_key_deriver! hmac = @key_deriver.create_hmac( data: data, protocol_id: protocol_id, key_id: key_id, counterparty: counterparty || 'self', privileged: privileged ) { hmac: hmac } end |
#create_signature(protocol_id:, key_id:, data: nil, hash_to_directly_sign: nil, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) ⇒ Object
608 609 610 611 612 613 614 615 616 617 618 |
# File 'lib/bsv/wallet/engine.rb', line 608 def create_signature(protocol_id:, key_id:, data: nil, hash_to_directly_sign: nil, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) require_key_deriver! signature = @key_deriver.create_signature( data: data, hash_to_directly_sign: hash_to_directly_sign, protocol_id: protocol_id, key_id: key_id, counterparty: counterparty || 'self', privileged: privileged ) { signature: signature } end |
#decrypt(ciphertext:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) ⇒ Object
573 574 575 576 577 578 579 580 581 582 |
# File 'lib/bsv/wallet/engine.rb', line 573 def decrypt(ciphertext:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) require_key_deriver! plaintext = @key_deriver.decrypt( ciphertext: ciphertext, protocol_id: protocol_id, key_id: key_id, counterparty: counterparty || 'self', privileged: privileged ) { plaintext: plaintext } end |
#discover_by_attributes(attributes:, limit: 10, offset: 0, seek_permission: true, originator: nil) ⇒ Object
699 700 701 702 703 704 705 |
# File 'lib/bsv/wallet/engine.rb', line 699 def discover_by_attributes(attributes:, limit: 10, offset: 0, seek_permission: true, originator: nil) # Local lookup — external discovery is a future concern # This requires scanning certificate fields, which the Store # doesn't support yet. Return empty for now. { total_certificates: 0, certificates: [] } end |
#discover_by_identity_key(identity_key:, limit: 10, offset: 0, seek_permission: true, originator: nil) ⇒ Object
687 688 689 690 691 692 693 694 695 696 697 |
# File 'lib/bsv/wallet/engine.rb', line 687 def discover_by_identity_key(identity_key:, limit: 10, offset: 0, seek_permission: true, originator: nil) # Local lookup — external discovery is a future concern result = @store.query_certificates( certifiers: [], types: [], limit: [limit, 10_000].min, offset: offset ) # Filter by subject (identity_key) in application layer matching = result[:certificates].select { |c| c[:subject] == identity_key } { total_certificates: matching.size, certificates: matching } end |
#encrypt(plaintext:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) ⇒ Object
— Cryptography Operations (codes 11-16) —
562 563 564 565 566 567 568 569 570 571 |
# File 'lib/bsv/wallet/engine.rb', line 562 def encrypt(plaintext:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) require_key_deriver! ciphertext = @key_deriver.encrypt( plaintext: plaintext, protocol_id: protocol_id, key_id: key_id, counterparty: counterparty || 'self', privileged: privileged ) { ciphertext: ciphertext } end |
#get_header_for_height(height:, originator: nil) ⇒ Object
725 726 727 |
# File 'lib/bsv/wallet/engine.rb', line 725 def get_header_for_height(height:, originator: nil) raise BSV::Wallet::UnsupportedActionError, 'get_header_for_height' end |
#get_height(originator: nil) ⇒ Object
— Blockchain and Network Data (codes 25-28) —
721 722 723 |
# File 'lib/bsv/wallet/engine.rb', line 721 def get_height(originator: nil) raise BSV::Wallet::UnsupportedActionError, 'get_height' end |
#get_network(originator: nil) ⇒ Object
729 730 731 |
# File 'lib/bsv/wallet/engine.rb', line 729 def get_network(originator: nil) { network: @network_name } end |
#get_public_key(identity_key: false, protocol_id: nil, key_id: nil, privileged: false, privileged_reason: nil, counterparty: nil, for_self: false, seek_permission: true, originator: nil) ⇒ Object
— Public Key Management (codes 8-10) —
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 |
# File 'lib/bsv/wallet/engine.rb', line 523 def get_public_key(identity_key: false, protocol_id: nil, key_id: nil, privileged: false, privileged_reason: nil, counterparty: nil, for_self: false, seek_permission: true, originator: nil) require_key_deriver! if identity_key { public_key: @key_deriver.identity_key } else pub = @key_deriver.derive_public_key( protocol_id: protocol_id, key_id: key_id, counterparty: counterparty || 'self', for_self: for_self, privileged: privileged ) { public_key: pub } end end |
#get_version(originator: nil) ⇒ Object
733 734 735 |
# File 'lib/bsv/wallet/engine.rb', line 733 def get_version(originator: nil) { version: "bsv-wallet-#{BSV::Wallet::VERSION}" } end |
#headroom ⇒ Object
How many sats can be spent before hitting the limp threshold.
56 57 58 |
# File 'lib/bsv/wallet/engine.rb', line 56 def headroom [@utxo_pool.balance - @limp_threshold, 0].max end |
#import_utxo(dtxid:, vout: 0) ⇒ Hash
Import a root-key UTXO and immediately pay to self on a derived address.
Rescues funds sent directly to the wallet’s root key (an error condition or bootstrap from a non-BRC-100 source). Fetches the transaction and merkle proof from the network provider, verifies the output is P2PKH to the wallet’s root key, imports it, then immediately spends it to a BRC-42 derived self-address. The root UTXO is promoted as spendable briefly, then consumed by the self-payment — only the derived output remains spendable after completion.
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
# File 'lib/bsv/wallet/engine.rb', line 342 def import_utxo(dtxid:, vout: 0) require_key_deriver! raise BSV::Wallet::Error, 'no network provider configured' unless @network_provider # Fetch transaction from network BSV.logger&.debug { "[Engine] import_utxo: fetching #{dtxid} from network" } result = @network_provider.call(:get_tx, txid: dtxid) raise BSV::Wallet::Error, "failed to fetch tx #{dtxid}" unless result.http_success? raw_tx = [result.data.strip].pack('H*') tx = BSV::Transaction::Transaction.from_binary(raw_tx) # Verify output exists and is P2PKH to our root key unless vout.is_a?(Integer) && vout >= 0 && vout < tx.outputs.length raise BSV::Wallet::InvalidParameterError.new('vout', "out of range (#{tx.outputs.length} outputs)") end output = tx.outputs[vout] locking_script = output.locking_script root_hash = @key_deriver.root_private_key.public_key.hash160 unless locking_script.p2pkh? && locking_script.chunks[2].data == root_hash raise BSV::Wallet::InvalidParameterError.new('vout', 'output is not P2PKH to the wallet root key') end satoshis = output.satoshis wtxid = tx.wtxid # Fetch merkle proof if mined merkle_path = nil block_height = nil details_result = @network_provider.call(:get_tx_details, txid: dtxid) if details_result.http_success? && details_result.data['blockheight'] block_height = details_result.data['blockheight'] proof_result = @network_provider.call(:get_merkle_path, txid: dtxid) if proof_result.http_success? && proof_result.data.is_a?(Array) && proof_result.data.any? tsc = proof_result.data.first mp = BSV::Transaction::MerklePath.from_tsc( dtxid_hex: tsc['txOrId'], index: tsc['index'], nodes: tsc['nodes'], block_height: block_height ) merkle_path = mp.to_binary end end BSV.logger&.debug { "[Engine] import_utxo: #{satoshis} sats at vout #{vout}, height=#{block_height || 'unconfirmed'}" } # Phase 1: Record the root-key UTXO import_action = @store.create_action( action: { description: 'imported UTXO', broadcast: :none, outgoing: false } ) @store.sign_action(action_id: import_action[:id], wtxid: wtxid, raw_tx: raw_tx) @proof_store.save_proof(wtxid: wtxid, proof: { raw_tx: raw_tx }) output_ids = @store.promote_action( action_id: import_action[:id], outputs: [{ satoshis: satoshis, vout: vout, locking_script: locking_script.to_binary, output_type: 'root' }] ) imported_output_id = output_ids.first # Store proof and link proof = { raw_tx: raw_tx, merkle_path: merkle_path, height: block_height }.compact if proof.any? proof_id = @proof_store.save_proof(wtxid: wtxid, proof: proof) @store.link_proof(action_id: import_action[:id], tx_proof_id: proof_id) end # Phase 2: Self-payment to derived address derivation_prefix = SecureRandom.uuid derivation_suffix = '1' derived_pub = @key_deriver.derive_public_key( protocol_id: [2, derivation_prefix], key_id: derivation_suffix, counterparty: 'self' ) derived_script = BSV::Script::Script.p2pkh_lock( BSV::Primitives::Digest.hash160(derived_pub) ).to_binary fee = 1 # token fee for no_send self-payment (BRC-67: inputs > outputs) self_payment_sats = satoshis - fee raise BSV::Wallet::Error, "insufficient sats for self-payment (#{satoshis} - #{fee} fee)" if self_payment_sats <= 0 # Bootstrap self-payment bypasses limp mode — this is how the # wallet gets funded in the first place. @bypass_limp_mode = true begin create_action( description: 'import self-payment', inputs: [{ output_id: imported_output_id }], outputs: [{ satoshis: self_payment_sats, locking_script: derived_script, derivation_prefix: derivation_prefix, derivation_suffix: derivation_suffix, sender_identity_key: @key_deriver.identity_key }], no_send: true, randomize_outputs: false ) ensure @bypass_limp_mode = false end BSV.logger&.debug { "[Engine] import_utxo complete: #{self_payment_sats} sats on derived address" } { imported: true, satoshis: self_payment_sats, dtxid: dtxid } end |
#import_wallet ⇒ Hash
Scan the root key’s address for unspent outputs and import each one.
Derives the P2PKH address from the wallet’s root key, queries the network for UTXOs, and calls import_utxo for each. This is the bootstrap path — how a wallet gets its initial funding.
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 |
# File 'lib/bsv/wallet/engine.rb', line 454 def import_wallet require_key_deriver! raise BSV::Wallet::Error, 'no network provider configured' unless @network_provider address = @key_deriver.root_private_key.public_key.address BSV.logger&.debug { "[Engine] import_wallet: scanning #{address}" } result = @network_provider.call(:get_utxos, address) raise BSV::Wallet::Error, "failed to fetch UTXOs for #{address}" unless result.http_success? utxos = result.data return { imported: 0, utxos: [] } if utxos.nil? || utxos.empty? imported = utxos.filter_map do |utxo| import_utxo(dtxid: utxo['tx_hash'], vout: utxo['tx_pos']) rescue BSV::Wallet::Error => e BSV.logger&.warn { "[Engine] import_wallet: skipping #{utxo['tx_hash']}:#{utxo['tx_pos']} — #{e.}" } nil end { imported: imported.length, utxos: imported } end |
#internalize_action(tx:, outputs:, description:, labels: nil, trust_self: nil, known_txids: nil, seek_permission: true, originator: nil) ⇒ Object
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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'lib/bsv/wallet/engine.rb', line 234 def internalize_action(tx:, outputs:, description:, labels: nil, trust_self: nil, known_txids: nil, seek_permission: true, originator: nil) validate_description!(description) # known_txids is the BRC-100 spec param name; values are wire-order wtxids known_txids&.each { |w| BSV::Primitives::Hex.validate_wtxid!(w, name: 'known_txids entry') } # Parse tx: as Atomic BEEF (BRC-95) beef, subject_tx = parse_beef(tx) # trustSelf: the sender may have included TXID-only entries for ancestors # they know we have. from_binary can't wire those (no Transaction object), # so hydrate any unresolved inputs from our ProofStore before verification. hydrate_known_sources!(subject_tx) if trust_self == 'known' # Full SPV verification: scripts, merkle proofs, and fee adequacy # (output <= input). Replaces the former validate_beef! + # validate_fee_adequacy! two-step. verify_incoming_transaction!(subject_tx) # Create action (incoming, no broadcast, already completed) action_result = @store.create_action( action: { description: description, broadcast: :none, outgoing: false } ) # Store wtxid and raw_tx on the action @store.sign_action( action_id: action_result[:id], wtxid: subject_tx.wtxid, raw_tx: subject_tx.to_binary ) @proof_store.save_proof(wtxid: subject_tx.wtxid, proof: { raw_tx: subject_tx.to_binary }) BSV.logger&.debug { "[Engine] internalize_action: subject=#{subject_tx.dtxid}" } attach_labels(action_result[:id], labels) # Save ancestor proofs BEFORE replacing known ancestors with TXID-only. # save_beef_proofs iterates beef.transactions and skips TxidOnlyEntry — # if we replaced first, ancestors listed in known_txids but not yet in # ProofStore would be converted to TXID-only and their proofs lost. save_beef_proofs(beef, subject_tx.wtxid, action_result[:id]) # trustSelf: replace known ancestors with TXID-only entries. # This runs AFTER save_beef_proofs so no proof data is lost, and # AFTER verify so the full graph was already validated. # make_txid_only replaces entries in the BEEF's @transactions list but # does NOT invalidate in-memory source_transaction pointers wired by # from_binary — verify already walked those pointers successfully above. replace_known_ancestors!(beef, subject_tx.wtxid, known_txids) if trust_self == 'known' output_specs = outputs.map do |out| spec = resolve_internalize_output(out) tx_out = subject_tx.outputs[spec[:vout]] unless tx_out raise BSV::Wallet::InvalidParameterError.new( 'output_index', "vout #{spec[:vout]} does not exist in subject transaction (#{subject_tx.outputs.length} outputs)" ) end spec[:locking_script] = tx_out.locking_script.to_binary if spec[:satoshis]&.positive? && spec[:satoshis] != tx_out.satoshis raise BSV::Wallet::InvalidParameterError.new( 'satoshis', "declared satoshis #{spec[:satoshis]} != transaction output #{tx_out.satoshis} at vout #{spec[:vout]}" ) end spec[:satoshis] = tx_out.satoshis spec end @store.promote_action(action_id: action_result[:id], outputs: output_specs) { accepted: true } end |
#limp_mode? ⇒ Boolean
Is the wallet in limp mode? When true, all outbound operations are blocked. The wallet can still receive to restore normal operations.
51 52 53 |
# File 'lib/bsv/wallet/engine.rb', line 51 def limp_mode? @utxo_pool.balance < @limp_threshold end |
#list_actions(labels:, label_query_mode: :any, include_labels: false, include_inputs: false, include_input_source_locking_scripts: false, include_input_unlocking_scripts: false, include_outputs: false, include_output_locking_scripts: false, limit: 10, offset: 0, seek_permission: true, originator: nil) ⇒ Object
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
# File 'lib/bsv/wallet/engine.rb', line 217 def list_actions(labels:, label_query_mode: :any, include_labels: false, include_inputs: false, include_input_source_locking_scripts: false, include_input_unlocking_scripts: false, include_outputs: false, include_output_locking_scripts: false, limit: 10, offset: 0, seek_permission: true, originator: nil) result = @store.query_actions( labels: labels, label_query_mode: label_query_mode, limit: [limit, 10_000].min, offset: offset, include_labels: include_labels, include_inputs: include_inputs, include_input_locking_scripts: include_input_source_locking_scripts, include_outputs: include_outputs, include_output_locking_scripts: include_output_locking_scripts ) { total_actions: result[:total], actions: result[:actions] } end |
#list_certificates(certifiers:, types:, limit: 10, offset: 0, privileged: false, privileged_reason: nil, originator: nil) ⇒ Object
661 662 663 664 665 666 667 668 |
# File 'lib/bsv/wallet/engine.rb', line 661 def list_certificates(certifiers:, types:, limit: 10, offset: 0, privileged: false, privileged_reason: nil, originator: nil) result = @store.query_certificates( certifiers: certifiers, types: types, limit: [limit, 10_000].min, offset: offset ) { total_certificates: result[:total], certificates: result[:certificates] } end |
#list_outputs(basket:, tags: nil, tag_query_mode: :any, include: nil, include_custom_instructions: false, include_tags: false, include_labels: false, limit: 10, offset: 0, seek_permission: true, originator: nil) ⇒ Object
308 309 310 311 312 313 314 315 316 317 318 319 320 |
# File 'lib/bsv/wallet/engine.rb', line 308 def list_outputs(basket:, tags: nil, tag_query_mode: :any, include: nil, include_custom_instructions: false, include_tags: false, include_labels: false, limit: 10, offset: 0, seek_permission: true, originator: nil) result = @store.query_outputs( basket: basket, tags: , tag_query_mode: tag_query_mode, limit: [limit, 10_000].min, offset: offset, include_locking_scripts: [:locking_scripts, 'locking scripts'].include?(include), include_custom_instructions: include_custom_instructions, include_tags: , include_labels: include_labels ) { total_outputs: result[:total], outputs: result[:outputs] } end |
#prove_certificate(certificate:, fields_to_reveal:, verifier:, privileged: false, privileged_reason: nil, originator: nil) ⇒ Object
670 671 672 673 674 675 676 677 678 679 680 |
# File 'lib/bsv/wallet/engine.rb', line 670 def prove_certificate(certificate:, fields_to_reveal:, verifier:, privileged: false, privileged_reason: nil, originator: nil) require_key_deriver! keyring = @key_deriver.derive_revelation_keyring( certificate: certificate, fields_to_reveal: fields_to_reveal, verifier: verifier, privileged: privileged ) { keyring_for_verifier: keyring } end |
#relinquish_certificate(type:, serial_number:, certifier:, originator: nil) ⇒ Object
682 683 684 685 |
# File 'lib/bsv/wallet/engine.rb', line 682 def relinquish_certificate(type:, serial_number:, certifier:, originator: nil) @store.delete_certificate(type: type, serial_number: serial_number, certifier: certifier) { relinquished: true } end |
#relinquish_output(basket:, output:, originator: nil) ⇒ Object
322 323 324 325 |
# File 'lib/bsv/wallet/engine.rb', line 322 def relinquish_output(basket:, output:, originator: nil) @store.relinquish_output(output_id: output) { relinquished: true } end |
#reveal_counterparty_key_linkage(counterparty:, verifier:, privileged: false, privileged_reason: nil, originator: nil) ⇒ Object
541 542 543 544 545 546 547 548 |
# File 'lib/bsv/wallet/engine.rb', line 541 def reveal_counterparty_key_linkage(counterparty:, verifier:, privileged: false, privileged_reason: nil, originator: nil) require_key_deriver! @key_deriver.reveal_counterparty_linkage( counterparty: counterparty, verifier: verifier, privileged: privileged ) end |
#reveal_specific_key_linkage(counterparty:, verifier:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, originator: nil) ⇒ Object
550 551 552 553 554 555 556 557 558 |
# File 'lib/bsv/wallet/engine.rb', line 550 def reveal_specific_key_linkage(counterparty:, verifier:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, originator: nil) require_key_deriver! @key_deriver.reveal_specific_linkage( counterparty: counterparty, verifier: verifier, protocol_id: protocol_id, key_id: key_id, privileged: privileged ) end |
#send_payment(recipient:, satoshis:) ⇒ Hash
Send a BRC-42 derived payment to a recipient.
Generates derivation parameters, derives a P2PKH locking script for the recipient via BRC-42, and calls create_action with auto-fund to handle UTXO selection, fees, and change.
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 |
# File 'lib/bsv/wallet/engine.rb', line 486 def send_payment(recipient:, satoshis:) require_key_deriver! validate_recipient_key!(recipient) derivation_prefix = SecureRandom.uuid derivation_suffix = '1' derived_pub = @key_deriver.derive_public_key( protocol_id: [2, derivation_prefix], key_id: derivation_suffix, counterparty: recipient, for_self: true ) locking_script = BSV::Script::Script.p2pkh_lock( BSV::Primitives::Digest.hash160(derived_pub) ).to_binary # randomize_outputs: false guarantees the payment output stays at # index 0. Auto-fund change outputs are appended after caller outputs. result = create_action( description: "send #{satoshis} sats", outputs: [{ satoshis: satoshis, locking_script: locking_script }], no_send: true, randomize_outputs: false ) { beef: result[:tx], sender_identity_key: @key_deriver.identity_key, outputs: [{ vout: 0, # relies on randomize_outputs: false — see above satoshis: satoshis, derivation_prefix: derivation_prefix, derivation_suffix: derivation_suffix }] } end |
#sign_action(spends:, reference:, accept_delayed_broadcast: true, return_txid_only: false, no_send: false, send_with: nil, originator: nil) ⇒ Object
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
# File 'lib/bsv/wallet/engine.rb', line 167 def sign_action(spends:, reference:, accept_delayed_broadcast: true, return_txid_only: false, no_send: false, send_with: nil, originator: nil) validate_reference!(reference) action = @store.find_action(reference: reference) raise BSV::Wallet::InvalidParameterError, 'reference' unless action # Outputs were already written during create_action — sign_action only # deserializes the unsigned tx, applies caller unlocking scripts, signs # remaining P2PKH inputs, and updates the action with signed raw_tx + wtxid. wtxid, raw_tx = apply_spends(action, spends) @store.sign_action(action_id: action[:id], wtxid: wtxid, raw_tx: raw_tx) @proof_store.save_proof(wtxid: wtxid, proof: { raw_tx: raw_tx }) # Build Atomic BEEF envelope for the :tx return value atomic_beef = build_atomic_beef(raw_tx, action[:id]) broadcast = determine_broadcast(no_send, accept_delayed_broadcast) if no_send result = { txid: wtxid, tx: atomic_beef } result[:send_with_results] = process_send_with(send_with) if send_with&.any? return result end unless broadcast == :none broadcast_result = @broadcast_queue.submit( action_id: action[:id], raw_tx: raw_tx, immediate: broadcast == :inline ) handle_proof_from_broadcast(action[:id], broadcast_result) if broadcast == :inline && accepted?(broadcast_result) end result = { txid: wtxid, tx: return_txid_only ? nil : atomic_beef } result[:send_with_results] = process_send_with(send_with) if send_with&.any? result end |
#verify_hmac(data:, hmac:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) ⇒ Object
595 596 597 598 599 600 601 602 603 604 605 606 |
# File 'lib/bsv/wallet/engine.rb', line 595 def verify_hmac(data:, hmac:, protocol_id:, key_id:, privileged: false, privileged_reason: nil, counterparty: nil, seek_permission: true, originator: nil) require_key_deriver! expected = @key_deriver.create_hmac( data: data, protocol_id: protocol_id, key_id: key_id, counterparty: counterparty || 'self', privileged: privileged ) raise BSV::Wallet::InvalidHmacError unless secure_compare(expected, hmac) { valid: true } end |
#verify_signature(signature:, protocol_id:, key_id:, data: nil, hash_to_directly_verify: nil, privileged: false, privileged_reason: nil, counterparty: nil, for_self: false, seek_permission: true, originator: nil) ⇒ Object
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 |
# File 'lib/bsv/wallet/engine.rb', line 620 def verify_signature(signature:, protocol_id:, key_id:, data: nil, hash_to_directly_verify: nil, privileged: false, privileged_reason: nil, counterparty: nil, for_self: false, seek_permission: true, originator: nil) require_key_deriver! valid = @key_deriver.verify_signature( signature: signature, data: data, hash_to_directly_verify: hash_to_directly_verify, protocol_id: protocol_id, key_id: key_id, counterparty: counterparty || 'self', for_self: for_self, privileged: privileged ) raise BSV::Wallet::InvalidSignatureError unless valid { valid: true } end |