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.

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