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