Class: ItsyBtc::Commands::SignCommand

Inherits:
Command
  • Object
show all
Defined in:
lib/itsy-btc/commands/sign_command.rb

Instance Attribute Summary

Attributes inherited from Command

#wallet

Instance Method Summary collapse

Methods inherited from Command

args, name, summary

Constructor Details

#initialize(tx_path) ⇒ SignCommand

Returns a new instance of SignCommand.



8
9
10
# File 'lib/itsy-btc/commands/sign_command.rb', line 8

def initialize(tx_path)
  @tx_path = tx_path
end

Instance Method Details

#runObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/itsy-btc/commands/sign_command.rb', line 12

def run
  if @wallet.nil?
    puts "No wallet found! Use `itsy init` to create one."
    exit
  end

  tx = Bitcoin::Protocol::Tx.from_json_file(@tx_path)

  inputs_signed = 0
  tx.in.each.with_index do |txin, i|
    script = Bitcoin::Script.new(txin.script_sig)
    if script.type == :unknown
      puts "Input ##{i} already signed!"
      inputs_signed += 1
    else
      address = case script.type
                  when :hash160
                    script.get_hash160_address
                  when :pubkey
                    script.get_pubkey_address
                  else
                    nil
                  end
      if address
        if base58_key = @wallet.key_for_address(address)
          key = Bitcoin.open_key(Bitcoin::Key.from_base58(base58_key).priv)
          sig = Bitcoin.sign_data(key, tx.signature_hash_for_input(i, nil, txin.script_sig))
          txin.script_sig = Bitcoin::Script.to_signature_pubkey_script(sig, [key.public_key_hex].pack("H*"))
          puts "Input ##{i} signed."
          inputs_signed += 1
        else
          puts "Input ##{i} to address #{address} cannot be signed, that address is not in your wallet!"
        end
      else
        puts "Input ##{i} cannot be signed, its script type is #{script.type} which is unsupported."
      end
    end
  end

  tx = Bitcoin::Protocol::Tx.new(tx.to_payload)

  if inputs_signed == 0
    puts "No inputs signed."
  elsif inputs_signed == tx.in.length
    File.open("#{tx.hash}-signed.json", "w") { |f| f << tx.to_json }
    puts "Transaction signed, saved to #{tx.hash}-signed.json."
  else
    File.open("#{tx.hash}-signed#{inputs_signed}.json", "w") { |f| f << tx.to_json }
    puts "#{inputs_signed} of #{tx.in.length} inputs signed, saved to #{tx.hash}-signed#{inputs_signed}.json."
  end
end