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.

434 lines
13 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
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
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
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
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
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
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
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
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
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
6 years ago
  1. package privval
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "time"
  8. "github.com/tendermint/tendermint/crypto"
  9. "github.com/tendermint/tendermint/crypto/ed25519"
  10. tmbytes "github.com/tendermint/tendermint/libs/bytes"
  11. tmos "github.com/tendermint/tendermint/libs/os"
  12. "github.com/tendermint/tendermint/libs/tempfile"
  13. "github.com/tendermint/tendermint/types"
  14. tmtime "github.com/tendermint/tendermint/types/time"
  15. )
  16. // TODO: type ?
  17. const (
  18. stepNone int8 = 0 // Used to distinguish the initial state
  19. stepPropose int8 = 1
  20. stepPrevote int8 = 2
  21. stepPrecommit int8 = 3
  22. )
  23. // A vote is either stepPrevote or stepPrecommit.
  24. func voteToStep(vote *types.Vote) int8 {
  25. switch vote.Type {
  26. case types.PrevoteType:
  27. return stepPrevote
  28. case types.PrecommitType:
  29. return stepPrecommit
  30. default:
  31. panic("Unknown vote type")
  32. }
  33. }
  34. //-------------------------------------------------------------------------------
  35. // FilePVKey stores the immutable part of PrivValidator.
  36. type FilePVKey struct {
  37. Address types.Address `json:"address"`
  38. PubKey crypto.PubKey `json:"pub_key"`
  39. PrivKey crypto.PrivKey `json:"priv_key"`
  40. filePath string
  41. }
  42. // Save persists the FilePVKey to its filePath.
  43. func (pvKey FilePVKey) Save() {
  44. outFile := pvKey.filePath
  45. if outFile == "" {
  46. panic("cannot save PrivValidator key: filePath not set")
  47. }
  48. jsonBytes, err := cdc.MarshalJSONIndent(pvKey, "", " ")
  49. if err != nil {
  50. panic(err)
  51. }
  52. err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0600)
  53. if err != nil {
  54. panic(err)
  55. }
  56. }
  57. //-------------------------------------------------------------------------------
  58. // FilePVLastSignState stores the mutable part of PrivValidator.
  59. type FilePVLastSignState struct {
  60. Height int64 `json:"height"`
  61. Round int `json:"round"`
  62. Step int8 `json:"step"`
  63. Signature []byte `json:"signature,omitempty"`
  64. SignBytes tmbytes.HexBytes `json:"signbytes,omitempty"`
  65. filePath string
  66. }
  67. // CheckHRS checks the given height, round, step (HRS) against that of the
  68. // FilePVLastSignState. It returns an error if the arguments constitute a regression,
  69. // or if they match but the SignBytes are empty.
  70. // The returned boolean indicates whether the last Signature should be reused -
  71. // it returns true if the HRS matches the arguments and the SignBytes are not empty (indicating
  72. // we have already signed for this HRS, and can reuse the existing signature).
  73. // It panics if the HRS matches the arguments, there's a SignBytes, but no Signature.
  74. func (lss *FilePVLastSignState) CheckHRS(height int64, round int, step int8) (bool, error) {
  75. if lss.Height > height {
  76. return false, fmt.Errorf("height regression. Got %v, last height %v", height, lss.Height)
  77. }
  78. if lss.Height == height {
  79. if lss.Round > round {
  80. return false, fmt.Errorf("round regression at height %v. Got %v, last round %v", height, round, lss.Round)
  81. }
  82. if lss.Round == round {
  83. if lss.Step > step {
  84. return false, fmt.Errorf(
  85. "step regression at height %v round %v. Got %v, last step %v",
  86. height,
  87. round,
  88. step,
  89. lss.Step,
  90. )
  91. } else if lss.Step == step {
  92. if lss.SignBytes != nil {
  93. if lss.Signature == nil {
  94. panic("pv: Signature is nil but SignBytes is not!")
  95. }
  96. return true, nil
  97. }
  98. return false, errors.New("no SignBytes found")
  99. }
  100. }
  101. }
  102. return false, nil
  103. }
  104. // Save persists the FilePvLastSignState to its filePath.
  105. func (lss *FilePVLastSignState) Save() {
  106. outFile := lss.filePath
  107. if outFile == "" {
  108. panic("cannot save FilePVLastSignState: filePath not set")
  109. }
  110. jsonBytes, err := cdc.MarshalJSONIndent(lss, "", " ")
  111. if err != nil {
  112. panic(err)
  113. }
  114. err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0600)
  115. if err != nil {
  116. panic(err)
  117. }
  118. }
  119. //-------------------------------------------------------------------------------
  120. // FilePV implements PrivValidator using data persisted to disk
  121. // to prevent double signing.
  122. // NOTE: the directories containing pv.Key.filePath and pv.LastSignState.filePath must already exist.
  123. // It includes the LastSignature and LastSignBytes so we don't lose the signature
  124. // if the process crashes after signing but before the resulting consensus message is processed.
  125. type FilePV struct {
  126. Key FilePVKey
  127. LastSignState FilePVLastSignState
  128. }
  129. // GenFilePV generates a new validator with randomly generated private key
  130. // and sets the filePaths, but does not call Save().
  131. func GenFilePV(keyFilePath, stateFilePath string) *FilePV {
  132. privKey := ed25519.GenPrivKey()
  133. return &FilePV{
  134. Key: FilePVKey{
  135. Address: privKey.PubKey().Address(),
  136. PubKey: privKey.PubKey(),
  137. PrivKey: privKey,
  138. filePath: keyFilePath,
  139. },
  140. LastSignState: FilePVLastSignState{
  141. Step: stepNone,
  142. filePath: stateFilePath,
  143. },
  144. }
  145. }
  146. // LoadFilePV loads a FilePV from the filePaths. The FilePV handles double
  147. // signing prevention by persisting data to the stateFilePath. If either file path
  148. // does not exist, the program will exit.
  149. func LoadFilePV(keyFilePath, stateFilePath string) *FilePV {
  150. return loadFilePV(keyFilePath, stateFilePath, true)
  151. }
  152. // LoadFilePVEmptyState loads a FilePV from the given keyFilePath, with an empty LastSignState.
  153. // If the keyFilePath does not exist, the program will exit.
  154. func LoadFilePVEmptyState(keyFilePath, stateFilePath string) *FilePV {
  155. return loadFilePV(keyFilePath, stateFilePath, false)
  156. }
  157. // If loadState is true, we load from the stateFilePath. Otherwise, we use an empty LastSignState.
  158. func loadFilePV(keyFilePath, stateFilePath string, loadState bool) *FilePV {
  159. keyJSONBytes, err := ioutil.ReadFile(keyFilePath)
  160. if err != nil {
  161. tmos.Exit(err.Error())
  162. }
  163. pvKey := FilePVKey{}
  164. err = cdc.UnmarshalJSON(keyJSONBytes, &pvKey)
  165. if err != nil {
  166. tmos.Exit(fmt.Sprintf("Error reading PrivValidator key from %v: %v\n", keyFilePath, err))
  167. }
  168. // overwrite pubkey and address for convenience
  169. pvKey.PubKey = pvKey.PrivKey.PubKey()
  170. pvKey.Address = pvKey.PubKey.Address()
  171. pvKey.filePath = keyFilePath
  172. pvState := FilePVLastSignState{}
  173. if loadState {
  174. stateJSONBytes, err := ioutil.ReadFile(stateFilePath)
  175. if err != nil {
  176. tmos.Exit(err.Error())
  177. }
  178. err = cdc.UnmarshalJSON(stateJSONBytes, &pvState)
  179. if err != nil {
  180. tmos.Exit(fmt.Sprintf("Error reading PrivValidator state from %v: %v\n", stateFilePath, err))
  181. }
  182. }
  183. pvState.filePath = stateFilePath
  184. return &FilePV{
  185. Key: pvKey,
  186. LastSignState: pvState,
  187. }
  188. }
  189. // LoadOrGenFilePV loads a FilePV from the given filePaths
  190. // or else generates a new one and saves it to the filePaths.
  191. func LoadOrGenFilePV(keyFilePath, stateFilePath string) *FilePV {
  192. var pv *FilePV
  193. if tmos.FileExists(keyFilePath) {
  194. pv = LoadFilePV(keyFilePath, stateFilePath)
  195. } else {
  196. pv = GenFilePV(keyFilePath, stateFilePath)
  197. pv.Save()
  198. }
  199. return pv
  200. }
  201. // GetAddress returns the address of the validator.
  202. // Implements PrivValidator.
  203. func (pv *FilePV) GetAddress() types.Address {
  204. return pv.Key.Address
  205. }
  206. // GetPubKey returns the public key of the validator.
  207. // Implements PrivValidator.
  208. func (pv *FilePV) GetPubKey() crypto.PubKey {
  209. return pv.Key.PubKey
  210. }
  211. // SignVote signs a canonical representation of the vote, along with the
  212. // chainID. Implements PrivValidator.
  213. func (pv *FilePV) SignVote(chainID string, vote *types.Vote) error {
  214. if err := pv.signVote(chainID, vote); err != nil {
  215. return fmt.Errorf("error signing vote: %v", err)
  216. }
  217. return nil
  218. }
  219. // SignProposal signs a canonical representation of the proposal, along with
  220. // the chainID. Implements PrivValidator.
  221. func (pv *FilePV) SignProposal(chainID string, proposal *types.Proposal) error {
  222. if err := pv.signProposal(chainID, proposal); err != nil {
  223. return fmt.Errorf("error signing proposal: %v", err)
  224. }
  225. return nil
  226. }
  227. // Save persists the FilePV to disk.
  228. func (pv *FilePV) Save() {
  229. pv.Key.Save()
  230. pv.LastSignState.Save()
  231. }
  232. // Reset resets all fields in the FilePV.
  233. // NOTE: Unsafe!
  234. func (pv *FilePV) Reset() {
  235. var sig []byte
  236. pv.LastSignState.Height = 0
  237. pv.LastSignState.Round = 0
  238. pv.LastSignState.Step = 0
  239. pv.LastSignState.Signature = sig
  240. pv.LastSignState.SignBytes = nil
  241. pv.Save()
  242. }
  243. // String returns a string representation of the FilePV.
  244. func (pv *FilePV) String() string {
  245. return fmt.Sprintf(
  246. "PrivValidator{%v LH:%v, LR:%v, LS:%v}",
  247. pv.GetAddress(),
  248. pv.LastSignState.Height,
  249. pv.LastSignState.Round,
  250. pv.LastSignState.Step,
  251. )
  252. }
  253. //------------------------------------------------------------------------------------
  254. // signVote checks if the vote is good to sign and sets the vote signature.
  255. // It may need to set the timestamp as well if the vote is otherwise the same as
  256. // a previously signed vote (ie. we crashed after signing but before the vote hit the WAL).
  257. func (pv *FilePV) signVote(chainID string, vote *types.Vote) error {
  258. height, round, step := vote.Height, vote.Round, voteToStep(vote)
  259. lss := pv.LastSignState
  260. sameHRS, err := lss.CheckHRS(height, round, step)
  261. if err != nil {
  262. return err
  263. }
  264. signBytes := vote.SignBytes(chainID)
  265. // We might crash before writing to the wal,
  266. // causing us to try to re-sign for the same HRS.
  267. // If signbytes are the same, use the last signature.
  268. // If they only differ by timestamp, use last timestamp and signature
  269. // Otherwise, return error
  270. if sameHRS {
  271. if bytes.Equal(signBytes, lss.SignBytes) {
  272. vote.Signature = lss.Signature
  273. } else if timestamp, ok := checkVotesOnlyDifferByTimestamp(lss.SignBytes, signBytes); ok {
  274. vote.Timestamp = timestamp
  275. vote.Signature = lss.Signature
  276. } else {
  277. err = fmt.Errorf("conflicting data")
  278. }
  279. return err
  280. }
  281. // It passed the checks. Sign the vote
  282. sig, err := pv.Key.PrivKey.Sign(signBytes)
  283. if err != nil {
  284. return err
  285. }
  286. pv.saveSigned(height, round, step, signBytes, sig)
  287. vote.Signature = sig
  288. return nil
  289. }
  290. // signProposal checks if the proposal is good to sign and sets the proposal signature.
  291. // It may need to set the timestamp as well if the proposal is otherwise the same as
  292. // a previously signed proposal ie. we crashed after signing but before the proposal hit the WAL).
  293. func (pv *FilePV) signProposal(chainID string, proposal *types.Proposal) error {
  294. height, round, step := proposal.Height, proposal.Round, stepPropose
  295. lss := pv.LastSignState
  296. sameHRS, err := lss.CheckHRS(height, round, step)
  297. if err != nil {
  298. return err
  299. }
  300. signBytes := proposal.SignBytes(chainID)
  301. // We might crash before writing to the wal,
  302. // causing us to try to re-sign for the same HRS.
  303. // If signbytes are the same, use the last signature.
  304. // If they only differ by timestamp, use last timestamp and signature
  305. // Otherwise, return error
  306. if sameHRS {
  307. if bytes.Equal(signBytes, lss.SignBytes) {
  308. proposal.Signature = lss.Signature
  309. } else if timestamp, ok := checkProposalsOnlyDifferByTimestamp(lss.SignBytes, signBytes); ok {
  310. proposal.Timestamp = timestamp
  311. proposal.Signature = lss.Signature
  312. } else {
  313. err = fmt.Errorf("conflicting data")
  314. }
  315. return err
  316. }
  317. // It passed the checks. Sign the proposal
  318. sig, err := pv.Key.PrivKey.Sign(signBytes)
  319. if err != nil {
  320. return err
  321. }
  322. pv.saveSigned(height, round, step, signBytes, sig)
  323. proposal.Signature = sig
  324. return nil
  325. }
  326. // Persist height/round/step and signature
  327. func (pv *FilePV) saveSigned(height int64, round int, step int8,
  328. signBytes []byte, sig []byte) {
  329. pv.LastSignState.Height = height
  330. pv.LastSignState.Round = round
  331. pv.LastSignState.Step = step
  332. pv.LastSignState.Signature = sig
  333. pv.LastSignState.SignBytes = signBytes
  334. pv.LastSignState.Save()
  335. }
  336. //-----------------------------------------------------------------------------------------
  337. // returns the timestamp from the lastSignBytes.
  338. // returns true if the only difference in the votes is their timestamp.
  339. func checkVotesOnlyDifferByTimestamp(lastSignBytes, newSignBytes []byte) (time.Time, bool) {
  340. var lastVote, newVote types.CanonicalVote
  341. if err := cdc.UnmarshalBinaryLengthPrefixed(lastSignBytes, &lastVote); err != nil {
  342. panic(fmt.Sprintf("LastSignBytes cannot be unmarshalled into vote: %v", err))
  343. }
  344. if err := cdc.UnmarshalBinaryLengthPrefixed(newSignBytes, &newVote); err != nil {
  345. panic(fmt.Sprintf("signBytes cannot be unmarshalled into vote: %v", err))
  346. }
  347. lastTime := lastVote.Timestamp
  348. // set the times to the same value and check equality
  349. now := tmtime.Now()
  350. lastVote.Timestamp = now
  351. newVote.Timestamp = now
  352. lastVoteBytes, _ := cdc.MarshalJSON(lastVote)
  353. newVoteBytes, _ := cdc.MarshalJSON(newVote)
  354. return lastTime, bytes.Equal(newVoteBytes, lastVoteBytes)
  355. }
  356. // returns the timestamp from the lastSignBytes.
  357. // returns true if the only difference in the proposals is their timestamp
  358. func checkProposalsOnlyDifferByTimestamp(lastSignBytes, newSignBytes []byte) (time.Time, bool) {
  359. var lastProposal, newProposal types.CanonicalProposal
  360. if err := cdc.UnmarshalBinaryLengthPrefixed(lastSignBytes, &lastProposal); err != nil {
  361. panic(fmt.Sprintf("LastSignBytes cannot be unmarshalled into proposal: %v", err))
  362. }
  363. if err := cdc.UnmarshalBinaryLengthPrefixed(newSignBytes, &newProposal); err != nil {
  364. panic(fmt.Sprintf("signBytes cannot be unmarshalled into proposal: %v", err))
  365. }
  366. lastTime := lastProposal.Timestamp
  367. // set the times to the same value and check equality
  368. now := tmtime.Now()
  369. lastProposal.Timestamp = now
  370. newProposal.Timestamp = now
  371. lastProposalBytes, _ := cdc.MarshalBinaryLengthPrefixed(lastProposal)
  372. newProposalBytes, _ := cdc.MarshalBinaryLengthPrefixed(newProposal)
  373. return lastTime, bytes.Equal(newProposalBytes, lastProposalBytes)
  374. }