message.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. // Copyright 2017 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. "encoding/hex"
  19. "fmt"
  20. "os"
  21. "github.com/ethereum/go-ethereum/accounts"
  22. "github.com/ethereum/go-ethereum/accounts/keystore"
  23. "github.com/ethereum/go-ethereum/cmd/utils"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/urfave/cli/v2"
  27. )
  28. type outputSign struct {
  29. Signature string
  30. }
  31. var msgfileFlag = &cli.StringFlag{
  32. Name: "msgfile",
  33. Usage: "file containing the message to sign/verify",
  34. }
  35. var commandSignMessage = &cli.Command{
  36. Name: "signmessage",
  37. Usage: "sign a message",
  38. ArgsUsage: "<keyfile> <message>",
  39. Description: `
  40. Sign the message with a keyfile.
  41. To sign a message contained in a file, use the --msgfile flag.
  42. `,
  43. Flags: []cli.Flag{
  44. passphraseFlag,
  45. jsonFlag,
  46. msgfileFlag,
  47. },
  48. Action: func(ctx *cli.Context) error {
  49. message := getMessage(ctx, 1)
  50. // Load the keyfile.
  51. keyfilepath := ctx.Args().First()
  52. keyjson, err := os.ReadFile(keyfilepath)
  53. if err != nil {
  54. utils.Fatalf("Failed to read the keyfile at '%s': %v", keyfilepath, err)
  55. }
  56. // Decrypt key with passphrase.
  57. passphrase := getPassphrase(ctx, false)
  58. key, err := keystore.DecryptKey(keyjson, passphrase)
  59. if err != nil {
  60. utils.Fatalf("Error decrypting key: %v", err)
  61. }
  62. signature, err := crypto.Sign(accounts.TextHash(message), key.PrivateKey)
  63. if err != nil {
  64. utils.Fatalf("Failed to sign message: %v", err)
  65. }
  66. out := outputSign{Signature: hex.EncodeToString(signature)}
  67. if ctx.Bool(jsonFlag.Name) {
  68. mustPrintJSON(out)
  69. } else {
  70. fmt.Println("Signature:", out.Signature)
  71. }
  72. return nil
  73. },
  74. }
  75. type outputVerify struct {
  76. Success bool
  77. RecoveredAddress string
  78. RecoveredPublicKey string
  79. }
  80. var commandVerifyMessage = &cli.Command{
  81. Name: "verifymessage",
  82. Usage: "verify the signature of a signed message",
  83. ArgsUsage: "<address> <signature> <message>",
  84. Description: `
  85. Verify the signature of the message.
  86. It is possible to refer to a file containing the message.`,
  87. Flags: []cli.Flag{
  88. jsonFlag,
  89. msgfileFlag,
  90. },
  91. Action: func(ctx *cli.Context) error {
  92. addressStr := ctx.Args().First()
  93. signatureHex := ctx.Args().Get(1)
  94. message := getMessage(ctx, 2)
  95. if !common.IsHexAddress(addressStr) {
  96. utils.Fatalf("Invalid address: %s", addressStr)
  97. }
  98. address := common.HexToAddress(addressStr)
  99. signature, err := hex.DecodeString(signatureHex)
  100. if err != nil {
  101. utils.Fatalf("Signature encoding is not hexadecimal: %v", err)
  102. }
  103. recoveredPubkey, err := crypto.SigToPub(accounts.TextHash(message), signature)
  104. if err != nil || recoveredPubkey == nil {
  105. utils.Fatalf("Signature verification failed: %v", err)
  106. }
  107. recoveredPubkeyBytes := crypto.FromECDSAPub(recoveredPubkey)
  108. recoveredAddress := crypto.PubkeyToAddress(*recoveredPubkey)
  109. success := address == recoveredAddress
  110. out := outputVerify{
  111. Success: success,
  112. RecoveredPublicKey: hex.EncodeToString(recoveredPubkeyBytes),
  113. RecoveredAddress: recoveredAddress.Hex(),
  114. }
  115. if ctx.Bool(jsonFlag.Name) {
  116. mustPrintJSON(out)
  117. } else {
  118. if out.Success {
  119. fmt.Println("Signature verification successful!")
  120. } else {
  121. fmt.Println("Signature verification failed!")
  122. }
  123. fmt.Println("Recovered public key:", out.RecoveredPublicKey)
  124. fmt.Println("Recovered address:", out.RecoveredAddress)
  125. }
  126. return nil
  127. },
  128. }
  129. func getMessage(ctx *cli.Context, msgarg int) []byte {
  130. if file := ctx.String(msgfileFlag.Name); file != "" {
  131. if ctx.NArg() > msgarg {
  132. utils.Fatalf("Can't use --msgfile and message argument at the same time.")
  133. }
  134. msg, err := os.ReadFile(file)
  135. if err != nil {
  136. utils.Fatalf("Can't read message file: %v", err)
  137. }
  138. return msg
  139. } else if ctx.NArg() == msgarg+1 {
  140. return []byte(ctx.Args().Get(msgarg))
  141. }
  142. utils.Fatalf("Invalid number of arguments: want %d, got %d", msgarg+1, ctx.NArg())
  143. return nil
  144. }