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