github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/portxo/addwif.go (about) 1 package portxo 2 3 import ( 4 "bytes" 5 "fmt" 6 7 "github.com/mit-dci/lit/logging" 8 9 "github.com/mit-dci/lit/btcutil" 10 "github.com/mit-dci/lit/coinparam" 11 ) 12 13 func (u *PorTxo) AddWIF(w btcutil.WIF) error { 14 var err error 15 16 // check that WIF and utxo net ID match 17 18 //... which is super annoying because the wif netID is not capitalized. 19 // so we'll capitalize it and be able to check just by matching bytes. 20 21 // if u.NetID != w.netID { 22 // return fmt.Errorf("utxo and wif key networks don't match") 23 // } 24 25 // if TxoMode is set, check that compressed / uncompressed match 26 if u.Mode != TxoUnknownMode { 27 if w.CompressPubKey && u.Mode&FlagTxoCompressed == 0 { 28 return fmt.Errorf("utxo %s uncompressed, but WIF key is compressed", 29 u.Op.String()) 30 } 31 if !w.CompressPubKey && u.Mode&FlagTxoCompressed != 0 { 32 return fmt.Errorf("utxo %s compressed, but WIF key is uncompressed", 33 u.Op.String()) 34 } 35 } 36 37 // if script exists and mode is set to PKH, check if pubkey matches script 38 if u.PkScript != nil && (u.Mode&FlagTxoPubKeyHash != 0) { 39 // just check testnet and mainnet for now, can add more later. 40 // annoying that WIF can't return params... it should... 41 42 adr := new(btcutil.AddressPubKeyHash) 43 44 if w.IsForNet(&coinparam.TestNet3Params) { 45 // generate address from wif key 46 adr, err = btcutil.NewAddressPubKeyHash( 47 btcutil.Hash160(w.SerializePubKey()), &coinparam.TestNet3Params) 48 if err != nil { 49 return err 50 } 51 } else { // assume mainnet 52 // generate address from wif key 53 adr, err = btcutil.NewAddressPubKeyHash( 54 btcutil.Hash160(w.SerializePubKey()), &coinparam.BitcoinParams) 55 if err != nil { 56 return err 57 } 58 } 59 if len(u.PkScript) != 25 { 60 return fmt.Errorf("pkh utxo script %d bytes (not 25)", len(u.PkScript)) 61 } 62 if !bytes.Equal(adr.ScriptAddress(), u.PkScript[3:23]) { 63 logging.Errorf("utxopk:\t%x\nwifpk:\t%x\n", 64 u.PkScript[3:23], adr.ScriptAddress()) 65 return fmt.Errorf("utxo and wif addresses don't match") 66 } 67 } 68 69 // everything OK, copy in private key 70 copy(u.PrivKey[:], w.PrivKey.Serialize()) 71 72 return nil 73 }