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.

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