exec.go 11 KB

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