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.

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