github.com/piotrnar/gocoin@v0.0.0-20240512203912-faa0448c5e96/tools/txaddsig/txaddsig.go (about)

     1  package main
     2  
     3  import (
     4  	"os"
     5  	"fmt"
     6  	"bytes"
     7  	"strconv"
     8  	"io/ioutil"
     9  	"encoding/hex"
    10  	"github.com/piotrnar/gocoin/lib/btc"
    11  )
    12  
    13  
    14  func raw_tx_from_file(fn string) *btc.Tx {
    15  	d, er := ioutil.ReadFile(fn)
    16  	if er != nil {
    17  		fmt.Println(er.Error())
    18  		return nil
    19  	}
    20  
    21  	dat, er := hex.DecodeString(string(d))
    22  	if er != nil {
    23  		fmt.Println("hex.DecodeString failed - assume binary transaction file")
    24  		dat = d
    25  	}
    26  	tx, txle := btc.NewTx(dat)
    27  
    28  	if tx != nil && txle != len(dat) {
    29  		fmt.Println("WARNING: Raw transaction length mismatch", txle, len(dat))
    30  	}
    31  
    32  	return tx
    33  }
    34  
    35  
    36  func write_tx_file(tx *btc.Tx) {
    37  	signedrawtx := tx.Serialize()
    38  	tx.SetHash(signedrawtx)
    39  
    40  	hs := tx.Hash.String()
    41  	fmt.Println(hs)
    42  
    43  	f, _ := os.Create(hs[:8]+".txt")
    44  	if f != nil {
    45  		f.Write([]byte(hex.EncodeToString(signedrawtx)))
    46  		f.Close()
    47  		fmt.Println("Transaction data stored in", hs[:8]+".txt")
    48  	}
    49  }
    50  
    51  
    52  func main() {
    53  	if len(os.Args)!=5 {
    54  		fmt.Println("This tool needs to be executed with 4 arguments:")
    55  		fmt.Println(" 1) Name of the unsigned transaction file")
    56  		fmt.Println(" 2) Input index to add the key & signature to")
    57  		fmt.Println(" 3) Hex dump of the canonical signature")
    58  		fmt.Println(" 4) Hex dump of the public key")
    59  		return
    60  	}
    61  	tx := raw_tx_from_file(os.Args[1])
    62  	if tx==nil {
    63  		return
    64  	}
    65  
    66  	in, er := strconv.ParseUint(os.Args[2], 10, 32)
    67  	if er != nil {
    68  		println("Input index:", er.Error())
    69  		return
    70  	}
    71  
    72  	if int(in) >= len(tx.TxIn) {
    73  		println("Input index too big:", int(in), "/", len(tx.TxIn))
    74  		return
    75  	}
    76  
    77  	sig, er := hex.DecodeString(os.Args[3])
    78  	if er != nil {
    79  		println("Signature:", er.Error())
    80  		return
    81  	}
    82  
    83  	pk, er := hex.DecodeString(os.Args[4])
    84  	if er != nil {
    85  		println("Public key:", er.Error())
    86  		return
    87  	}
    88  
    89  	buf := new(bytes.Buffer)
    90  	btc.WriteVlen(buf, uint64(len(sig)))
    91  	buf.Write(sig)
    92  	btc.WriteVlen(buf, uint64(len(pk)))
    93  	buf.Write(pk)
    94  
    95  	tx.TxIn[in].ScriptSig = buf.Bytes()
    96  
    97  	write_tx_file(tx)
    98  }