10 "github.com/vapor/consensus"
11 "github.com/vapor/crypto/ed25519"
12 "github.com/vapor/crypto/ed25519/chainkd"
13 chainjson "github.com/vapor/encoding/json"
14 "github.com/vapor/equity/compiler"
17 var lockWith2of3KeysFmt = `
18 contract LockWith2of3Keys(%s) locks amount of asset {
19 clause unlockWith2Sigs(%s) {
20 verify checkTxMultiSig(%s)
21 unlock amount of asset
26 func GetPeginContractPrograms(claimScript []byte) ([]byte, error) {
28 pubkeys := getNewXpub(consensus.ActiveNetParams.FedpegXPubs, claimScript)
31 return nil, errors.New("Fedpeg's XPubs is empty")
37 for index := 0; index < num; index++ {
38 param := fmt.Sprintf("pubkey%d", index+1)
41 if (index + 1) < num {
46 params += ": PublicKey"
49 signNum := getNumberOfSignaturesRequired(pubkeys)
50 for index := 0; index < signNum; index++ {
51 param := fmt.Sprintf("sig%d", index+1)
54 if index+1 < signNum {
60 unlockParams += ": Signature"
63 lockWith2of3Keys := fmt.Sprintf(lockWith2of3KeysFmt, params, unlockParams, checkParams)
64 r := strings.NewReader(lockWith2of3Keys)
65 compiled, err := compiler.Compile(r)
67 return nil, errors.New("Compile contract failed")
70 contract := compiled[len(compiled)-1]
72 if num < len(contract.Params) {
73 return nil, errors.New("Compile contract failed")
76 contractArgs, err := convertArguments(contract, pubkeys)
78 fmt.Println("Convert arguments into contract parameters error:", err)
79 return nil, errors.New("Convert arguments into contract parameters error")
82 instantProg, err := instantiateContract(contract, contractArgs)
84 fmt.Println("Instantiate contract error:", err)
85 return nil, errors.New("Instantiate contract error")
88 return instantProg, nil
91 func getNewXpub(federationRedeemXPub []chainkd.XPub, claimScript []byte) []ed25519.PublicKey {
93 var pubkeys []ed25519.PublicKey
94 for _, xpub := range federationRedeemXPub {
95 // pub + scriptPubKey 生成一个随机数A
97 h := hmac.New(sha256.New, xpub[:])
99 tweak := h.Sum(tmp[:])
100 // pub + A 生成一个新的公钥pub_new
101 chaildXPub := xpub.Child(tweak)
102 pubkeys = append(pubkeys, chaildXPub.PublicKey())
107 func getNumberOfSignaturesRequired(pubkeys []ed25519.PublicKey) int {
108 return len(pubkeys)/2 + 1
111 // InstantiateContract instantiate contract parameters
112 func instantiateContract(contract *compiler.Contract, args []compiler.ContractArg) ([]byte, error) {
113 program, err := compiler.Instantiate(contract.Body, contract.Params, contract.Recursive, args)
121 func convertArguments(contract *compiler.Contract, args []ed25519.PublicKey) ([]compiler.ContractArg, error) {
122 var contractArgs []compiler.ContractArg
123 for i, p := range contract.Params {
124 var argument compiler.ContractArg
127 argument.S = (*chainjson.HexBytes)(&args[i])
129 return nil, errors.New("Contract parameter type error")
131 contractArgs = append(contractArgs, argument)
134 return contractArgs, nil