github.com/Deepchain-foundation/go-ethereum@v1.9.7/cmd/checkpoint-admin/exec.go (about)

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