exec.go 9.9 KB

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