You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

452 lines
14 KiB

Close and retry a RemoteSigner on err (#2923) * Close and recreate a RemoteSigner on err * Update changelog * Address Anton's comments / suggestions: - update changelog - restart TCPVal - shut down on `ErrUnexpectedResponse` * re-init remote signer client with fresh connection if Ping fails - add/update TODOs in secret connection - rename tcp.go -> tcp_client.go, same with ipc to clarify their purpose * account for `conn returned by waitConnection can be `nil` - also add TODO about RemoteSigner conn field * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn - add rwmutex for conn field in IPC * comments and doc.go * fix ipc tests. fixes #2677 * use constants for tests * cleanup some error statements * fixes #2784, race in tests * remove print statement * minor fixes from review * update comment on sts spec * cosmetics * p2p/conn: add failing tests * p2p/conn: make SecretConnection thread safe * changelog * IPCVal signer refactor - use a .reset() method - don't use embedded RemoteSignerClient - guard RemoteSignerClient with mutex - drop the .conn - expose Close() on RemoteSignerClient * apply IPCVal refactor to TCPVal * remove mtx from RemoteSignerClient * consolidate IPCVal and TCPVal, fixes #3104 - done in tcp_client.go - now called SocketVal - takes a listener in the constructor - make tcpListener and unixListener contain all the differences * delete ipc files * introduce unix and tcp dialer for RemoteSigner * rename files - drop tcp_ prefix - rename priv_validator.go to file.go * bring back listener options * fix node * fix priv_val_server * fix node test * minor cleanup and comments
6 years ago
privval: improve Remote Signer implementation (#3351) This issue is related to #3107 This is a first renaming/refactoring step before reworking and removing heartbeats. As discussed with @Liamsi , we preferred to go for a couple of independent and separate PRs to simplify review work. The changes: Help to clarify the relation between the validator and remote signer endpoints Differentiate between timeouts and deadlines Prepare to encapsulate networking related code behind RemoteSigner in the next PR My intention is to separate and encapsulate the "network related" code from the actual signer. SignerRemote ---(uses/contains)--> SignerValidatorEndpoint <--(connects to)--> SignerServiceEndpoint ---> SignerService (future.. not here yet but would like to decouple too) All reconnection/heartbeat/whatever code goes in the endpoints. Signer[Remote/Service] do not need to know about that. I agree Endpoint may not be the perfect name. I tried to find something "Go-ish" enough. It is a common name in go-kit, kubernetes, etc. Right now: SignerValidatorEndpoint: handles the listener contains SignerRemote Implements the PrivValidator interface connects and sets a connection object in a contained SignerRemote delegates PrivValidator some calls to SignerRemote which in turn uses the conn object that was set externally SignerRemote: Implements the PrivValidator interface read/writes from a connection object directly handles heartbeats SignerServiceEndpoint: Does most things in a single place delegates to a PrivValidator IIRC. * cleanup * Refactoring step 1 * Refactoring step 2 * move messages to another file * mark for future work / next steps * mark deprecated classes in docs * Fix linter problems * additional linter fixes
5 years ago
privval: improve Remote Signer implementation (#3351) This issue is related to #3107 This is a first renaming/refactoring step before reworking and removing heartbeats. As discussed with @Liamsi , we preferred to go for a couple of independent and separate PRs to simplify review work. The changes: Help to clarify the relation between the validator and remote signer endpoints Differentiate between timeouts and deadlines Prepare to encapsulate networking related code behind RemoteSigner in the next PR My intention is to separate and encapsulate the "network related" code from the actual signer. SignerRemote ---(uses/contains)--> SignerValidatorEndpoint <--(connects to)--> SignerServiceEndpoint ---> SignerService (future.. not here yet but would like to decouple too) All reconnection/heartbeat/whatever code goes in the endpoints. Signer[Remote/Service] do not need to know about that. I agree Endpoint may not be the perfect name. I tried to find something "Go-ish" enough. It is a common name in go-kit, kubernetes, etc. Right now: SignerValidatorEndpoint: handles the listener contains SignerRemote Implements the PrivValidator interface connects and sets a connection object in a contained SignerRemote delegates PrivValidator some calls to SignerRemote which in turn uses the conn object that was set externally SignerRemote: Implements the PrivValidator interface read/writes from a connection object directly handles heartbeats SignerServiceEndpoint: Does most things in a single place delegates to a PrivValidator IIRC. * cleanup * Refactoring step 1 * Refactoring step 2 * move messages to another file * mark for future work / next steps * mark deprecated classes in docs * Fix linter problems * additional linter fixes
5 years ago
privval: improve Remote Signer implementation (#3351) This issue is related to #3107 This is a first renaming/refactoring step before reworking and removing heartbeats. As discussed with @Liamsi , we preferred to go for a couple of independent and separate PRs to simplify review work. The changes: Help to clarify the relation between the validator and remote signer endpoints Differentiate between timeouts and deadlines Prepare to encapsulate networking related code behind RemoteSigner in the next PR My intention is to separate and encapsulate the "network related" code from the actual signer. SignerRemote ---(uses/contains)--> SignerValidatorEndpoint <--(connects to)--> SignerServiceEndpoint ---> SignerService (future.. not here yet but would like to decouple too) All reconnection/heartbeat/whatever code goes in the endpoints. Signer[Remote/Service] do not need to know about that. I agree Endpoint may not be the perfect name. I tried to find something "Go-ish" enough. It is a common name in go-kit, kubernetes, etc. Right now: SignerValidatorEndpoint: handles the listener contains SignerRemote Implements the PrivValidator interface connects and sets a connection object in a contained SignerRemote delegates PrivValidator some calls to SignerRemote which in turn uses the conn object that was set externally SignerRemote: Implements the PrivValidator interface read/writes from a connection object directly handles heartbeats SignerServiceEndpoint: Does most things in a single place delegates to a PrivValidator IIRC. * cleanup * Refactoring step 1 * Refactoring step 2 * move messages to another file * mark for future work / next steps * mark deprecated classes in docs * Fix linter problems * additional linter fixes
5 years ago
privval: improve Remote Signer implementation (#3351) This issue is related to #3107 This is a first renaming/refactoring step before reworking and removing heartbeats. As discussed with @Liamsi , we preferred to go for a couple of independent and separate PRs to simplify review work. The changes: Help to clarify the relation between the validator and remote signer endpoints Differentiate between timeouts and deadlines Prepare to encapsulate networking related code behind RemoteSigner in the next PR My intention is to separate and encapsulate the "network related" code from the actual signer. SignerRemote ---(uses/contains)--> SignerValidatorEndpoint <--(connects to)--> SignerServiceEndpoint ---> SignerService (future.. not here yet but would like to decouple too) All reconnection/heartbeat/whatever code goes in the endpoints. Signer[Remote/Service] do not need to know about that. I agree Endpoint may not be the perfect name. I tried to find something "Go-ish" enough. It is a common name in go-kit, kubernetes, etc. Right now: SignerValidatorEndpoint: handles the listener contains SignerRemote Implements the PrivValidator interface connects and sets a connection object in a contained SignerRemote delegates PrivValidator some calls to SignerRemote which in turn uses the conn object that was set externally SignerRemote: Implements the PrivValidator interface read/writes from a connection object directly handles heartbeats SignerServiceEndpoint: Does most things in a single place delegates to a PrivValidator IIRC. * cleanup * Refactoring step 1 * Refactoring step 2 * move messages to another file * mark for future work / next steps * mark deprecated classes in docs * Fix linter problems * additional linter fixes
5 years ago
privval: improve Remote Signer implementation (#3351) This issue is related to #3107 This is a first renaming/refactoring step before reworking and removing heartbeats. As discussed with @Liamsi , we preferred to go for a couple of independent and separate PRs to simplify review work. The changes: Help to clarify the relation between the validator and remote signer endpoints Differentiate between timeouts and deadlines Prepare to encapsulate networking related code behind RemoteSigner in the next PR My intention is to separate and encapsulate the "network related" code from the actual signer. SignerRemote ---(uses/contains)--> SignerValidatorEndpoint <--(connects to)--> SignerServiceEndpoint ---> SignerService (future.. not here yet but would like to decouple too) All reconnection/heartbeat/whatever code goes in the endpoints. Signer[Remote/Service] do not need to know about that. I agree Endpoint may not be the perfect name. I tried to find something "Go-ish" enough. It is a common name in go-kit, kubernetes, etc. Right now: SignerValidatorEndpoint: handles the listener contains SignerRemote Implements the PrivValidator interface connects and sets a connection object in a contained SignerRemote delegates PrivValidator some calls to SignerRemote which in turn uses the conn object that was set externally SignerRemote: Implements the PrivValidator interface read/writes from a connection object directly handles heartbeats SignerServiceEndpoint: Does most things in a single place delegates to a PrivValidator IIRC. * cleanup * Refactoring step 1 * Refactoring step 2 * move messages to another file * mark for future work / next steps * mark deprecated classes in docs * Fix linter problems * additional linter fixes
5 years ago
privval: improve Remote Signer implementation (#3351) This issue is related to #3107 This is a first renaming/refactoring step before reworking and removing heartbeats. As discussed with @Liamsi , we preferred to go for a couple of independent and separate PRs to simplify review work. The changes: Help to clarify the relation between the validator and remote signer endpoints Differentiate between timeouts and deadlines Prepare to encapsulate networking related code behind RemoteSigner in the next PR My intention is to separate and encapsulate the "network related" code from the actual signer. SignerRemote ---(uses/contains)--> SignerValidatorEndpoint <--(connects to)--> SignerServiceEndpoint ---> SignerService (future.. not here yet but would like to decouple too) All reconnection/heartbeat/whatever code goes in the endpoints. Signer[Remote/Service] do not need to know about that. I agree Endpoint may not be the perfect name. I tried to find something "Go-ish" enough. It is a common name in go-kit, kubernetes, etc. Right now: SignerValidatorEndpoint: handles the listener contains SignerRemote Implements the PrivValidator interface connects and sets a connection object in a contained SignerRemote delegates PrivValidator some calls to SignerRemote which in turn uses the conn object that was set externally SignerRemote: Implements the PrivValidator interface read/writes from a connection object directly handles heartbeats SignerServiceEndpoint: Does most things in a single place delegates to a PrivValidator IIRC. * cleanup * Refactoring step 1 * Refactoring step 2 * move messages to another file * mark for future work / next steps * mark deprecated classes in docs * Fix linter problems * additional linter fixes
5 years ago
privval: improve Remote Signer implementation (#3351) This issue is related to #3107 This is a first renaming/refactoring step before reworking and removing heartbeats. As discussed with @Liamsi , we preferred to go for a couple of independent and separate PRs to simplify review work. The changes: Help to clarify the relation between the validator and remote signer endpoints Differentiate between timeouts and deadlines Prepare to encapsulate networking related code behind RemoteSigner in the next PR My intention is to separate and encapsulate the "network related" code from the actual signer. SignerRemote ---(uses/contains)--> SignerValidatorEndpoint <--(connects to)--> SignerServiceEndpoint ---> SignerService (future.. not here yet but would like to decouple too) All reconnection/heartbeat/whatever code goes in the endpoints. Signer[Remote/Service] do not need to know about that. I agree Endpoint may not be the perfect name. I tried to find something "Go-ish" enough. It is a common name in go-kit, kubernetes, etc. Right now: SignerValidatorEndpoint: handles the listener contains SignerRemote Implements the PrivValidator interface connects and sets a connection object in a contained SignerRemote delegates PrivValidator some calls to SignerRemote which in turn uses the conn object that was set externally SignerRemote: Implements the PrivValidator interface read/writes from a connection object directly handles heartbeats SignerServiceEndpoint: Does most things in a single place delegates to a PrivValidator IIRC. * cleanup * Refactoring step 1 * Refactoring step 2 * move messages to another file * mark for future work / next steps * mark deprecated classes in docs * Fix linter problems * additional linter fixes
5 years ago
privval: improve Remote Signer implementation (#3351) This issue is related to #3107 This is a first renaming/refactoring step before reworking and removing heartbeats. As discussed with @Liamsi , we preferred to go for a couple of independent and separate PRs to simplify review work. The changes: Help to clarify the relation between the validator and remote signer endpoints Differentiate between timeouts and deadlines Prepare to encapsulate networking related code behind RemoteSigner in the next PR My intention is to separate and encapsulate the "network related" code from the actual signer. SignerRemote ---(uses/contains)--> SignerValidatorEndpoint <--(connects to)--> SignerServiceEndpoint ---> SignerService (future.. not here yet but would like to decouple too) All reconnection/heartbeat/whatever code goes in the endpoints. Signer[Remote/Service] do not need to know about that. I agree Endpoint may not be the perfect name. I tried to find something "Go-ish" enough. It is a common name in go-kit, kubernetes, etc. Right now: SignerValidatorEndpoint: handles the listener contains SignerRemote Implements the PrivValidator interface connects and sets a connection object in a contained SignerRemote delegates PrivValidator some calls to SignerRemote which in turn uses the conn object that was set externally SignerRemote: Implements the PrivValidator interface read/writes from a connection object directly handles heartbeats SignerServiceEndpoint: Does most things in a single place delegates to a PrivValidator IIRC. * cleanup * Refactoring step 1 * Refactoring step 2 * move messages to another file * mark for future work / next steps * mark deprecated classes in docs * Fix linter problems * additional linter fixes
5 years ago
privval: improve Remote Signer implementation (#3351) This issue is related to #3107 This is a first renaming/refactoring step before reworking and removing heartbeats. As discussed with @Liamsi , we preferred to go for a couple of independent and separate PRs to simplify review work. The changes: Help to clarify the relation between the validator and remote signer endpoints Differentiate between timeouts and deadlines Prepare to encapsulate networking related code behind RemoteSigner in the next PR My intention is to separate and encapsulate the "network related" code from the actual signer. SignerRemote ---(uses/contains)--> SignerValidatorEndpoint <--(connects to)--> SignerServiceEndpoint ---> SignerService (future.. not here yet but would like to decouple too) All reconnection/heartbeat/whatever code goes in the endpoints. Signer[Remote/Service] do not need to know about that. I agree Endpoint may not be the perfect name. I tried to find something "Go-ish" enough. It is a common name in go-kit, kubernetes, etc. Right now: SignerValidatorEndpoint: handles the listener contains SignerRemote Implements the PrivValidator interface connects and sets a connection object in a contained SignerRemote delegates PrivValidator some calls to SignerRemote which in turn uses the conn object that was set externally SignerRemote: Implements the PrivValidator interface read/writes from a connection object directly handles heartbeats SignerServiceEndpoint: Does most things in a single place delegates to a PrivValidator IIRC. * cleanup * Refactoring step 1 * Refactoring step 2 * move messages to another file * mark for future work / next steps * mark deprecated classes in docs * Fix linter problems * additional linter fixes
5 years ago
  1. package privval
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "time"
  9. "github.com/gogo/protobuf/proto"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/crypto/ed25519"
  12. "github.com/tendermint/tendermint/crypto/secp256k1"
  13. "github.com/tendermint/tendermint/internal/libs/protoio"
  14. "github.com/tendermint/tendermint/internal/libs/tempfile"
  15. tmbytes "github.com/tendermint/tendermint/libs/bytes"
  16. tmjson "github.com/tendermint/tendermint/libs/json"
  17. tmos "github.com/tendermint/tendermint/libs/os"
  18. tmtime "github.com/tendermint/tendermint/libs/time"
  19. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  20. "github.com/tendermint/tendermint/types"
  21. )
  22. // TODO: type ?
  23. const (
  24. stepNone int8 = 0 // Used to distinguish the initial state
  25. stepPropose int8 = 1
  26. stepPrevote int8 = 2
  27. stepPrecommit int8 = 3
  28. )
  29. // A vote is either stepPrevote or stepPrecommit.
  30. func voteToStep(vote *tmproto.Vote) int8 {
  31. switch vote.Type {
  32. case tmproto.PrevoteType:
  33. return stepPrevote
  34. case tmproto.PrecommitType:
  35. return stepPrecommit
  36. default:
  37. panic(fmt.Sprintf("Unknown vote type: %v", vote.Type))
  38. }
  39. }
  40. //-------------------------------------------------------------------------------
  41. // FilePVKey stores the immutable part of PrivValidator.
  42. type FilePVKey struct {
  43. Address types.Address `json:"address"`
  44. PubKey crypto.PubKey `json:"pub_key"`
  45. PrivKey crypto.PrivKey `json:"priv_key"`
  46. filePath string
  47. }
  48. // Save persists the FilePVKey to its filePath.
  49. func (pvKey FilePVKey) Save() {
  50. outFile := pvKey.filePath
  51. if outFile == "" {
  52. panic("cannot save PrivValidator key: filePath not set")
  53. }
  54. jsonBytes, err := tmjson.MarshalIndent(pvKey, "", " ")
  55. if err != nil {
  56. panic(err)
  57. }
  58. err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0600)
  59. if err != nil {
  60. panic(err)
  61. }
  62. }
  63. //-------------------------------------------------------------------------------
  64. // FilePVLastSignState stores the mutable part of PrivValidator.
  65. type FilePVLastSignState struct {
  66. Height int64 `json:"height"`
  67. Round int32 `json:"round"`
  68. Step int8 `json:"step"`
  69. Signature []byte `json:"signature,omitempty"`
  70. SignBytes tmbytes.HexBytes `json:"signbytes,omitempty"`
  71. filePath string
  72. }
  73. // CheckHRS checks the given height, round, step (HRS) against that of the
  74. // FilePVLastSignState. It returns an error if the arguments constitute a regression,
  75. // or if they match but the SignBytes are empty.
  76. // The returned boolean indicates whether the last Signature should be reused -
  77. // it returns true if the HRS matches the arguments and the SignBytes are not empty (indicating
  78. // we have already signed for this HRS, and can reuse the existing signature).
  79. // It panics if the HRS matches the arguments, there's a SignBytes, but no Signature.
  80. func (lss *FilePVLastSignState) CheckHRS(height int64, round int32, step int8) (bool, error) {
  81. if lss.Height > height {
  82. return false, fmt.Errorf("height regression. Got %v, last height %v", height, lss.Height)
  83. }
  84. if lss.Height == height {
  85. if lss.Round > round {
  86. return false, fmt.Errorf("round regression at height %v. Got %v, last round %v", height, round, lss.Round)
  87. }
  88. if lss.Round == round {
  89. if lss.Step > step {
  90. return false, fmt.Errorf(
  91. "step regression at height %v round %v. Got %v, last step %v",
  92. height,
  93. round,
  94. step,
  95. lss.Step,
  96. )
  97. } else if lss.Step == step {
  98. if lss.SignBytes != nil {
  99. if lss.Signature == nil {
  100. panic("pv: Signature is nil but SignBytes is not!")
  101. }
  102. return true, nil
  103. }
  104. return false, errors.New("no SignBytes found")
  105. }
  106. }
  107. }
  108. return false, nil
  109. }
  110. // Save persists the FilePvLastSignState to its filePath.
  111. func (lss *FilePVLastSignState) Save() {
  112. outFile := lss.filePath
  113. if outFile == "" {
  114. panic("cannot save FilePVLastSignState: filePath not set")
  115. }
  116. jsonBytes, err := tmjson.MarshalIndent(lss, "", " ")
  117. if err != nil {
  118. panic(err)
  119. }
  120. err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0600)
  121. if err != nil {
  122. panic(err)
  123. }
  124. }
  125. //-------------------------------------------------------------------------------
  126. // FilePV implements PrivValidator using data persisted to disk
  127. // to prevent double signing.
  128. // NOTE: the directories containing pv.Key.filePath and pv.LastSignState.filePath must already exist.
  129. // It includes the LastSignature and LastSignBytes so we don't lose the signature
  130. // if the process crashes after signing but before the resulting consensus message is processed.
  131. type FilePV struct {
  132. Key FilePVKey
  133. LastSignState FilePVLastSignState
  134. }
  135. var _ types.PrivValidator = (*FilePV)(nil)
  136. // NewFilePV generates a new validator from the given key and paths.
  137. func NewFilePV(privKey crypto.PrivKey, keyFilePath, stateFilePath string) *FilePV {
  138. return &FilePV{
  139. Key: FilePVKey{
  140. Address: privKey.PubKey().Address(),
  141. PubKey: privKey.PubKey(),
  142. PrivKey: privKey,
  143. filePath: keyFilePath,
  144. },
  145. LastSignState: FilePVLastSignState{
  146. Step: stepNone,
  147. filePath: stateFilePath,
  148. },
  149. }
  150. }
  151. // GenFilePV generates a new validator with randomly generated private key
  152. // and sets the filePaths, but does not call Save().
  153. func GenFilePV(keyFilePath, stateFilePath, keyType string) (*FilePV, error) {
  154. switch keyType {
  155. case types.ABCIPubKeyTypeSecp256k1:
  156. return NewFilePV(secp256k1.GenPrivKey(), keyFilePath, stateFilePath), nil
  157. case "", types.ABCIPubKeyTypeEd25519:
  158. return NewFilePV(ed25519.GenPrivKey(), keyFilePath, stateFilePath), nil
  159. default:
  160. return nil, fmt.Errorf("key type: %s is not supported", keyType)
  161. }
  162. }
  163. // LoadFilePV loads a FilePV from the filePaths. The FilePV handles double
  164. // signing prevention by persisting data to the stateFilePath. If either file path
  165. // does not exist, the program will exit.
  166. func LoadFilePV(keyFilePath, stateFilePath string) (*FilePV, error) {
  167. return loadFilePV(keyFilePath, stateFilePath, true)
  168. }
  169. // LoadFilePVEmptyState loads a FilePV from the given keyFilePath, with an empty LastSignState.
  170. // If the keyFilePath does not exist, the program will exit.
  171. func LoadFilePVEmptyState(keyFilePath, stateFilePath string) (*FilePV, error) {
  172. return loadFilePV(keyFilePath, stateFilePath, false)
  173. }
  174. // If loadState is true, we load from the stateFilePath. Otherwise, we use an empty LastSignState.
  175. func loadFilePV(keyFilePath, stateFilePath string, loadState bool) (*FilePV, error) {
  176. keyJSONBytes, err := os.ReadFile(keyFilePath)
  177. if err != nil {
  178. return nil, err
  179. }
  180. pvKey := FilePVKey{}
  181. err = tmjson.Unmarshal(keyJSONBytes, &pvKey)
  182. if err != nil {
  183. return nil, fmt.Errorf("error reading PrivValidator key from %v: %w", keyFilePath, err)
  184. }
  185. // overwrite pubkey and address for convenience
  186. pvKey.PubKey = pvKey.PrivKey.PubKey()
  187. pvKey.Address = pvKey.PubKey.Address()
  188. pvKey.filePath = keyFilePath
  189. pvState := FilePVLastSignState{}
  190. if loadState {
  191. stateJSONBytes, err := os.ReadFile(stateFilePath)
  192. if err != nil {
  193. return nil, err
  194. }
  195. err = tmjson.Unmarshal(stateJSONBytes, &pvState)
  196. if err != nil {
  197. return nil, fmt.Errorf("error reading PrivValidator state from %v: %w", stateFilePath, err)
  198. }
  199. }
  200. pvState.filePath = stateFilePath
  201. return &FilePV{
  202. Key: pvKey,
  203. LastSignState: pvState,
  204. }, nil
  205. }
  206. // LoadOrGenFilePV loads a FilePV from the given filePaths
  207. // or else generates a new one and saves it to the filePaths.
  208. func LoadOrGenFilePV(keyFilePath, stateFilePath string) (*FilePV, error) {
  209. var (
  210. pv *FilePV
  211. err error
  212. )
  213. if tmos.FileExists(keyFilePath) {
  214. pv, err = LoadFilePV(keyFilePath, stateFilePath)
  215. } else {
  216. pv, err = GenFilePV(keyFilePath, stateFilePath, "")
  217. pv.Save()
  218. }
  219. return pv, err
  220. }
  221. // GetAddress returns the address of the validator.
  222. // Implements PrivValidator.
  223. func (pv *FilePV) GetAddress() types.Address {
  224. return pv.Key.Address
  225. }
  226. // GetPubKey returns the public key of the validator.
  227. // Implements PrivValidator.
  228. func (pv *FilePV) GetPubKey(ctx context.Context) (crypto.PubKey, error) {
  229. return pv.Key.PubKey, nil
  230. }
  231. // SignVote signs a canonical representation of the vote, along with the
  232. // chainID. Implements PrivValidator.
  233. func (pv *FilePV) SignVote(ctx context.Context, chainID string, vote *tmproto.Vote) error {
  234. if err := pv.signVote(chainID, vote); err != nil {
  235. return fmt.Errorf("error signing vote: %v", err)
  236. }
  237. return nil
  238. }
  239. // SignProposal signs a canonical representation of the proposal, along with
  240. // the chainID. Implements PrivValidator.
  241. func (pv *FilePV) SignProposal(ctx context.Context, chainID string, proposal *tmproto.Proposal) error {
  242. if err := pv.signProposal(chainID, proposal); err != nil {
  243. return fmt.Errorf("error signing proposal: %v", err)
  244. }
  245. return nil
  246. }
  247. // Save persists the FilePV to disk.
  248. func (pv *FilePV) Save() {
  249. pv.Key.Save()
  250. pv.LastSignState.Save()
  251. }
  252. // Reset resets all fields in the FilePV.
  253. // NOTE: Unsafe!
  254. func (pv *FilePV) Reset() {
  255. var sig []byte
  256. pv.LastSignState.Height = 0
  257. pv.LastSignState.Round = 0
  258. pv.LastSignState.Step = 0
  259. pv.LastSignState.Signature = sig
  260. pv.LastSignState.SignBytes = nil
  261. pv.Save()
  262. }
  263. // String returns a string representation of the FilePV.
  264. func (pv *FilePV) String() string {
  265. return fmt.Sprintf(
  266. "PrivValidator{%v LH:%v, LR:%v, LS:%v}",
  267. pv.GetAddress(),
  268. pv.LastSignState.Height,
  269. pv.LastSignState.Round,
  270. pv.LastSignState.Step,
  271. )
  272. }
  273. //------------------------------------------------------------------------------------
  274. // signVote checks if the vote is good to sign and sets the vote signature.
  275. // It may need to set the timestamp as well if the vote is otherwise the same as
  276. // a previously signed vote (ie. we crashed after signing but before the vote hit the WAL).
  277. func (pv *FilePV) signVote(chainID string, vote *tmproto.Vote) error {
  278. height, round, step := vote.Height, vote.Round, voteToStep(vote)
  279. lss := pv.LastSignState
  280. sameHRS, err := lss.CheckHRS(height, round, step)
  281. if err != nil {
  282. return err
  283. }
  284. signBytes := types.VoteSignBytes(chainID, vote)
  285. // We might crash before writing to the wal,
  286. // causing us to try to re-sign for the same HRS.
  287. // If signbytes are the same, use the last signature.
  288. // If they only differ by timestamp, use last timestamp and signature
  289. // Otherwise, return error
  290. if sameHRS {
  291. if bytes.Equal(signBytes, lss.SignBytes) {
  292. vote.Signature = lss.Signature
  293. } else if timestamp, ok := checkVotesOnlyDifferByTimestamp(lss.SignBytes, signBytes); ok {
  294. vote.Timestamp = timestamp
  295. vote.Signature = lss.Signature
  296. } else {
  297. err = fmt.Errorf("conflicting data")
  298. }
  299. return err
  300. }
  301. // It passed the checks. Sign the vote
  302. sig, err := pv.Key.PrivKey.Sign(signBytes)
  303. if err != nil {
  304. return err
  305. }
  306. pv.saveSigned(height, round, step, signBytes, sig)
  307. vote.Signature = sig
  308. return nil
  309. }
  310. // signProposal checks if the proposal is good to sign and sets the proposal signature.
  311. // It may need to set the timestamp as well if the proposal is otherwise the same as
  312. // a previously signed proposal ie. we crashed after signing but before the proposal hit the WAL).
  313. func (pv *FilePV) signProposal(chainID string, proposal *tmproto.Proposal) error {
  314. height, round, step := proposal.Height, proposal.Round, stepPropose
  315. lss := pv.LastSignState
  316. sameHRS, err := lss.CheckHRS(height, round, step)
  317. if err != nil {
  318. return err
  319. }
  320. signBytes := types.ProposalSignBytes(chainID, proposal)
  321. // We might crash before writing to the wal,
  322. // causing us to try to re-sign for the same HRS.
  323. // If signbytes are the same, use the last signature.
  324. // If they only differ by timestamp, use last timestamp and signature
  325. // Otherwise, return error
  326. if sameHRS {
  327. if bytes.Equal(signBytes, lss.SignBytes) {
  328. proposal.Signature = lss.Signature
  329. } else if timestamp, ok := checkProposalsOnlyDifferByTimestamp(lss.SignBytes, signBytes); ok {
  330. proposal.Timestamp = timestamp
  331. proposal.Signature = lss.Signature
  332. } else {
  333. err = fmt.Errorf("conflicting data")
  334. }
  335. return err
  336. }
  337. // It passed the checks. Sign the proposal
  338. sig, err := pv.Key.PrivKey.Sign(signBytes)
  339. if err != nil {
  340. return err
  341. }
  342. pv.saveSigned(height, round, step, signBytes, sig)
  343. proposal.Signature = sig
  344. return nil
  345. }
  346. // Persist height/round/step and signature
  347. func (pv *FilePV) saveSigned(height int64, round int32, step int8,
  348. signBytes []byte, sig []byte) {
  349. pv.LastSignState.Height = height
  350. pv.LastSignState.Round = round
  351. pv.LastSignState.Step = step
  352. pv.LastSignState.Signature = sig
  353. pv.LastSignState.SignBytes = signBytes
  354. pv.LastSignState.Save()
  355. }
  356. //-----------------------------------------------------------------------------------------
  357. // returns the timestamp from the lastSignBytes.
  358. // returns true if the only difference in the votes is their timestamp.
  359. func checkVotesOnlyDifferByTimestamp(lastSignBytes, newSignBytes []byte) (time.Time, bool) {
  360. var lastVote, newVote tmproto.CanonicalVote
  361. if err := protoio.UnmarshalDelimited(lastSignBytes, &lastVote); err != nil {
  362. panic(fmt.Sprintf("LastSignBytes cannot be unmarshalled into vote: %v", err))
  363. }
  364. if err := protoio.UnmarshalDelimited(newSignBytes, &newVote); err != nil {
  365. panic(fmt.Sprintf("signBytes cannot be unmarshalled into vote: %v", err))
  366. }
  367. lastTime := lastVote.Timestamp
  368. // set the times to the same value and check equality
  369. now := tmtime.Now()
  370. lastVote.Timestamp = now
  371. newVote.Timestamp = now
  372. return lastTime, proto.Equal(&newVote, &lastVote)
  373. }
  374. // returns the timestamp from the lastSignBytes.
  375. // returns true if the only difference in the proposals is their timestamp
  376. func checkProposalsOnlyDifferByTimestamp(lastSignBytes, newSignBytes []byte) (time.Time, bool) {
  377. var lastProposal, newProposal tmproto.CanonicalProposal
  378. if err := protoio.UnmarshalDelimited(lastSignBytes, &lastProposal); err != nil {
  379. panic(fmt.Sprintf("LastSignBytes cannot be unmarshalled into proposal: %v", err))
  380. }
  381. if err := protoio.UnmarshalDelimited(newSignBytes, &newProposal); err != nil {
  382. panic(fmt.Sprintf("signBytes cannot be unmarshalled into proposal: %v", err))
  383. }
  384. lastTime := lastProposal.Timestamp
  385. // set the times to the same value and check equality
  386. now := tmtime.Now()
  387. lastProposal.Timestamp = now
  388. newProposal.Timestamp = now
  389. return lastTime, proto.Equal(&newProposal, &lastProposal)
  390. }