github.com/core-coin/go-core/v2@v2.1.9/cmd/checkpoint-admin/exec.go (about)

     1  // Copyright 2019 by the Authors
     2  // This file is part of go-core.
     3  //
     4  // go-core is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // go-core is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-core. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package main
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"encoding/binary"
    23  	"fmt"
    24  	"math/big"
    25  	"strings"
    26  	"time"
    27  
    28  	"gopkg.in/urfave/cli.v1"
    29  
    30  	"github.com/core-coin/go-core/v2/accounts"
    31  	"github.com/core-coin/go-core/v2/cmd/utils"
    32  	"github.com/core-coin/go-core/v2/common"
    33  	"github.com/core-coin/go-core/v2/common/hexutil"
    34  	"github.com/core-coin/go-core/v2/contracts/checkpointoracle"
    35  	"github.com/core-coin/go-core/v2/contracts/checkpointoracle/contract"
    36  	"github.com/core-coin/go-core/v2/crypto"
    37  	"github.com/core-coin/go-core/v2/log"
    38  	"github.com/core-coin/go-core/v2/params"
    39  	"github.com/core-coin/go-core/v2/rpc"
    40  	"github.com/core-coin/go-core/v2/xcbclient"
    41  )
    42  
    43  var commandDeploy = cli.Command{
    44  	Name:  "deploy",
    45  	Usage: "Deploy a new checkpoint oracle contract",
    46  	Flags: []cli.Flag{
    47  		nodeURLFlag,
    48  		clefURLFlag,
    49  		signerFlag,
    50  		signersFlag,
    51  		thresholdFlag,
    52  	},
    53  	Action: utils.MigrateFlags(deploy),
    54  }
    55  
    56  var commandSign = cli.Command{
    57  	Name:  "sign",
    58  	Usage: "Sign the checkpoint with the specified key",
    59  	Flags: []cli.Flag{
    60  		nodeURLFlag,
    61  		clefURLFlag,
    62  		signerFlag,
    63  		indexFlag,
    64  		hashFlag,
    65  		oracleFlag,
    66  	},
    67  	Action: utils.MigrateFlags(sign),
    68  }
    69  
    70  var commandPublish = cli.Command{
    71  	Name:  "publish",
    72  	Usage: "Publish a checkpoint into the oracle",
    73  	Flags: []cli.Flag{
    74  		nodeURLFlag,
    75  		clefURLFlag,
    76  		signerFlag,
    77  		indexFlag,
    78  		signaturesFlag,
    79  	},
    80  	Action: utils.MigrateFlags(publish),
    81  }
    82  
    83  // deploy deploys the checkpoint registrar contract.
    84  //
    85  // Note the network where the contract is deployed depends on
    86  // the network where the connected node is located.
    87  func deploy(ctx *cli.Context) error {
    88  	// Gather all the addresses that should be permitted to sign
    89  	var addrs []common.Address
    90  	for _, account := range strings.Split(ctx.String(signersFlag.Name), ",") {
    91  		if trimmed := strings.TrimSpace(account); !common.IsHexAddress(trimmed) {
    92  			utils.Fatalf("Invalid account in --signers: '%s'", trimmed)
    93  		}
    94  		addr, err := common.HexToAddress(account)
    95  		if err != nil {
    96  			utils.Fatalf("invalid account %v, err: %v", addr, err)
    97  		}
    98  		addrs = append(addrs, addr)
    99  	}
   100  	// Retrieve and validate the signing threshold
   101  	needed := ctx.Int(thresholdFlag.Name)
   102  	if needed == 0 || needed > len(addrs) {
   103  		utils.Fatalf("Invalid signature threshold %d", needed)
   104  	}
   105  	// Print a summary to ensure the user understands what they're signing
   106  	fmt.Printf("Deploying new checkpoint oracle:\n\n")
   107  	for i, addr := range addrs {
   108  		fmt.Printf("Admin %d => %s\n", i+1, addr.Hex())
   109  	}
   110  	fmt.Printf("\nSignatures needed to publish: %d\n", needed)
   111  
   112  	// setup clef signer, create an abigen transactor and an RPC client
   113  	transactor, client := newClefSigner(ctx), newClient(ctx)
   114  
   115  	// Deploy the checkpoint oracle
   116  	fmt.Println("Sending deploy request to Clef...")
   117  	oracle, tx, _, err := contract.DeployCheckpointOracle(transactor, client, addrs, big.NewInt(int64(params.CheckpointFrequency)),
   118  		big.NewInt(int64(params.CheckpointProcessConfirmations)), big.NewInt(int64(needed)))
   119  	if err != nil {
   120  		utils.Fatalf("Failed to deploy checkpoint oracle %v", err)
   121  	}
   122  	log.Info("Deployed checkpoint oracle", "address", oracle, "tx", tx.Hash().Hex())
   123  
   124  	return nil
   125  }
   126  
   127  // sign creates the signature for specific checkpoint
   128  // with local key. Only contract admins have the permission to
   129  // sign checkpoint.
   130  func sign(ctx *cli.Context) error {
   131  	var (
   132  		err     error
   133  		offline bool // The indicator whether we sign checkpoint by offline.
   134  		chash   common.Hash
   135  		cindex  uint64
   136  		address common.Address
   137  
   138  		node   *rpc.Client
   139  		oracle *checkpointoracle.CheckpointOracle
   140  	)
   141  	if !ctx.GlobalIsSet(nodeURLFlag.Name) {
   142  		// Offline mode signing
   143  		offline = true
   144  		if !ctx.IsSet(hashFlag.Name) {
   145  			utils.Fatalf("Please specify the checkpoint hash (--hash) to sign in offline mode")
   146  		}
   147  		chash = common.HexToHash(ctx.String(hashFlag.Name))
   148  
   149  		if !ctx.IsSet(indexFlag.Name) {
   150  			utils.Fatalf("Please specify checkpoint index (--index) to sign in offline mode")
   151  		}
   152  		cindex = ctx.Uint64(indexFlag.Name)
   153  
   154  		if !ctx.IsSet(oracleFlag.Name) {
   155  			utils.Fatalf("Please specify oracle address (--oracle) to sign in offline mode")
   156  		}
   157  		address, err = common.HexToAddress(ctx.String(oracleFlag.Name))
   158  		if err != nil {
   159  			utils.Fatalf("invalid account %v, err: %v", ctx.String(oracleFlag.Name), err)
   160  		}
   161  	} else {
   162  		// Interactive mode signing, retrieve the data from the remote node
   163  		node = newRPCClient(ctx.GlobalString(nodeURLFlag.Name))
   164  
   165  		checkpoint := getCheckpoint(ctx, node)
   166  		chash, cindex, address = checkpoint.Hash(), checkpoint.SectionIndex, getContractAddr(node)
   167  
   168  		// Check the validity of checkpoint
   169  		reqCtx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second)
   170  		defer cancelFn()
   171  
   172  		head, err := xcbclient.NewClient(node).HeaderByNumber(reqCtx, nil)
   173  		if err != nil {
   174  			return err
   175  		}
   176  		num := head.Number.Uint64()
   177  		if num < ((cindex+1)*params.CheckpointFrequency + params.CheckpointProcessConfirmations) {
   178  			utils.Fatalf("Invalid future checkpoint")
   179  		}
   180  		_, oracle = newContract(node)
   181  		latest, _, h, err := oracle.Contract().GetLatestCheckpoint(nil)
   182  		if err != nil {
   183  			return err
   184  		}
   185  		if cindex < latest {
   186  			utils.Fatalf("Checkpoint is too old")
   187  		}
   188  		if cindex == latest && (latest != 0 || h.Uint64() != 0) {
   189  			utils.Fatalf("Stale checkpoint, latest registered %d, given %d", latest, cindex)
   190  		}
   191  	}
   192  	var (
   193  		signature string
   194  		signer    string
   195  	)
   196  	// isAdmin checks whether the specified signer is admin.
   197  	isAdmin := func(addr common.Address) error {
   198  		signers, err := oracle.Contract().GetAllAdmin(nil)
   199  		if err != nil {
   200  			return err
   201  		}
   202  		for _, s := range signers {
   203  			if s == addr {
   204  				return nil
   205  			}
   206  		}
   207  		return fmt.Errorf("signer %v is not the admin", addr.Hex())
   208  	}
   209  	// Print to the user the data thy are about to sign
   210  	fmt.Printf("Oracle     => %s\n", address.Hex())
   211  	fmt.Printf("Index %4d => %s\n", cindex, chash.Hex())
   212  
   213  	// Sign checkpoint in clef mode.
   214  	signer = ctx.String(signerFlag.Name)
   215  
   216  	addr, err := common.HexToAddress(signer)
   217  	if err != nil {
   218  		utils.Fatalf("invalid account %v, err: %v", signer, err)
   219  	}
   220  	if !offline {
   221  		if err := isAdmin(addr); err != nil {
   222  			return err
   223  		}
   224  	}
   225  	clef := newRPCClient(ctx.String(clefURLFlag.Name))
   226  	p := make(map[string]string)
   227  	buf := make([]byte, 8)
   228  	binary.BigEndian.PutUint64(buf, cindex)
   229  	p["address"] = address.Hex()
   230  	p["message"] = hexutil.Encode(append(buf, chash.Bytes()...))
   231  
   232  	fmt.Println("Sending signing request to Clef...")
   233  	if err := clef.Call(&signature, "account_signData", accounts.MimetypeDataWithValidator, signer, p); err != nil {
   234  		utils.Fatalf("Failed to sign checkpoint, err %v", err)
   235  	}
   236  	fmt.Printf("Signer     => %s\n", signer)
   237  	fmt.Printf("Signature  => %s\n", signature)
   238  	return nil
   239  }
   240  
   241  // sighash calculates the hash of the data to sign for the checkpoint oracle.
   242  func sighash(index uint64, oracle common.Address, hash common.Hash) []byte {
   243  	buf := make([]byte, 8)
   244  	binary.BigEndian.PutUint64(buf, index)
   245  
   246  	data := append([]byte{0x19, 0x00}, append(oracle[:], append(buf, hash[:]...)...)...)
   247  	return crypto.SHA3(data)
   248  }
   249  
   250  // ecrecover calculates the sender address from a sighash and signature combo.
   251  func ecrecover(sighash []byte, sig []byte) common.Address {
   252  	signer, err := crypto.SigToPub(sighash, sig)
   253  	if err != nil {
   254  		utils.Fatalf("Failed to recover sender from signature %x: %v", sig, err)
   255  	}
   256  	return crypto.PubkeyToAddress(signer)
   257  }
   258  
   259  // publish registers the specified checkpoint which generated by connected node
   260  // with a authorised private key.
   261  func publish(ctx *cli.Context) error {
   262  	// Print the checkpoint oracle's current status to make sure we're interacting
   263  	// with the correct network and contract.
   264  	status(ctx)
   265  
   266  	// Gather the signatures from the CLI
   267  	var sigs [][]byte
   268  	for _, sig := range strings.Split(ctx.String(signaturesFlag.Name), ",") {
   269  		trimmed := strings.TrimPrefix(strings.TrimSpace(sig), "0x")
   270  		if len(trimmed) != crypto.ExtendedSignatureLength*2 {
   271  			utils.Fatalf("Invalid signature in --signature: '%s'", trimmed)
   272  		} else {
   273  			sigs = append(sigs, common.Hex2Bytes(trimmed))
   274  		}
   275  	}
   276  	// Retrieve the checkpoint we want to sign to sort the signatures
   277  	var (
   278  		client       = newRPCClient(ctx.GlobalString(nodeURLFlag.Name))
   279  		addr, oracle = newContract(client)
   280  		checkpoint   = getCheckpoint(ctx, client)
   281  		sighash      = sighash(checkpoint.SectionIndex, addr, checkpoint.Hash())
   282  	)
   283  	for i := 0; i < len(sigs); i++ {
   284  		for j := i + 1; j < len(sigs); j++ {
   285  			signerA := ecrecover(sighash, sigs[i])
   286  			signerB := ecrecover(sighash, sigs[j])
   287  			if bytes.Compare(signerA.Bytes(), signerB.Bytes()) > 0 {
   288  				sigs[i], sigs[j] = sigs[j], sigs[i]
   289  			}
   290  		}
   291  	}
   292  	// Retrieve recent header info to protect replay attack
   293  	reqCtx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second)
   294  	defer cancelFn()
   295  
   296  	head, err := xcbclient.NewClient(client).HeaderByNumber(reqCtx, nil)
   297  	if err != nil {
   298  		return err
   299  	}
   300  	num := head.Number.Uint64()
   301  	recent, err := xcbclient.NewClient(client).HeaderByNumber(reqCtx, big.NewInt(int64(num-128)))
   302  	if err != nil {
   303  		return err
   304  	}
   305  	// Print a summary of the operation that's going to be performed
   306  	fmt.Printf("Publishing %d => %s:\n\n", checkpoint.SectionIndex, checkpoint.Hash().Hex())
   307  	for i, sig := range sigs {
   308  		fmt.Printf("Signer %d => %s\n", i+1, ecrecover(sighash, sig).Hex())
   309  	}
   310  	fmt.Println()
   311  	fmt.Printf("Sentry number => %d\nSentry hash   => %s\n", recent.Number, recent.Hash().Hex())
   312  
   313  	// Publish the checkpoint into the oracle
   314  	fmt.Println("Sending publish request to Clef...")
   315  	tx, err := oracle.RegisterCheckpoint(newClefSigner(ctx), checkpoint.SectionIndex, checkpoint.Hash().Bytes(), recent.Number, recent.Hash(), sigs)
   316  	if err != nil {
   317  		utils.Fatalf("Register contract failed %v", err)
   318  	}
   319  	log.Info("Successfully registered checkpoint", "tx", tx.Hash().Hex())
   320  	return nil
   321  }