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.

438 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/tendermint/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. // NewFilePV generates a new validator from the given key and paths.
  134. func NewFilePV(privKey crypto.PrivKey, keyFilePath, stateFilePath string) *FilePV {
  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. // GenFilePV generates a new validator with randomly generated private key
  149. // and sets the filePaths, but does not call Save().
  150. func GenFilePV(keyFilePath, stateFilePath string) *FilePV {
  151. return NewFilePV(ed25519.GenPrivKey(), keyFilePath, stateFilePath)
  152. }
  153. // LoadFilePV loads a FilePV from the filePaths. The FilePV handles double
  154. // signing prevention by persisting data to the stateFilePath. If either file path
  155. // does not exist, the program will exit.
  156. func LoadFilePV(keyFilePath, stateFilePath string) *FilePV {
  157. return loadFilePV(keyFilePath, stateFilePath, true)
  158. }
  159. // LoadFilePVEmptyState loads a FilePV from the given keyFilePath, with an empty LastSignState.
  160. // If the keyFilePath does not exist, the program will exit.
  161. func LoadFilePVEmptyState(keyFilePath, stateFilePath string) *FilePV {
  162. return loadFilePV(keyFilePath, stateFilePath, false)
  163. }
  164. // If loadState is true, we load from the stateFilePath. Otherwise, we use an empty LastSignState.
  165. func loadFilePV(keyFilePath, stateFilePath string, loadState bool) *FilePV {
  166. keyJSONBytes, err := ioutil.ReadFile(keyFilePath)
  167. if err != nil {
  168. tmos.Exit(err.Error())
  169. }
  170. pvKey := FilePVKey{}
  171. err = tmjson.Unmarshal(keyJSONBytes, &pvKey)
  172. if err != nil {
  173. tmos.Exit(fmt.Sprintf("Error reading PrivValidator key from %v: %v\n", keyFilePath, err))
  174. }
  175. // overwrite pubkey and address for convenience
  176. pvKey.PubKey = pvKey.PrivKey.PubKey()
  177. pvKey.Address = pvKey.PubKey.Address()
  178. pvKey.filePath = keyFilePath
  179. pvState := FilePVLastSignState{}
  180. if loadState {
  181. stateJSONBytes, err := ioutil.ReadFile(stateFilePath)
  182. if err != nil {
  183. tmos.Exit(err.Error())
  184. }
  185. err = tmjson.Unmarshal(stateJSONBytes, &pvState)
  186. if err != nil {
  187. tmos.Exit(fmt.Sprintf("Error reading PrivValidator state from %v: %v\n", stateFilePath, err))
  188. }
  189. }
  190. pvState.filePath = stateFilePath
  191. return &FilePV{
  192. Key: pvKey,
  193. LastSignState: pvState,
  194. }
  195. }
  196. // LoadOrGenFilePV loads a FilePV from the given filePaths
  197. // or else generates a new one and saves it to the filePaths.
  198. func LoadOrGenFilePV(keyFilePath, stateFilePath string) *FilePV {
  199. var pv *FilePV
  200. if tmos.FileExists(keyFilePath) {
  201. pv = LoadFilePV(keyFilePath, stateFilePath)
  202. } else {
  203. pv = GenFilePV(keyFilePath, stateFilePath)
  204. pv.Save()
  205. }
  206. return pv
  207. }
  208. // GetAddress returns the address of the validator.
  209. // Implements PrivValidator.
  210. func (pv *FilePV) GetAddress() types.Address {
  211. return pv.Key.Address
  212. }
  213. // GetPubKey returns the public key of the validator.
  214. // Implements PrivValidator.
  215. func (pv *FilePV) GetPubKey() (crypto.PubKey, error) {
  216. return pv.Key.PubKey, nil
  217. }
  218. // SignVote signs a canonical representation of the vote, along with the
  219. // chainID. Implements PrivValidator.
  220. func (pv *FilePV) SignVote(chainID string, vote *tmproto.Vote) error {
  221. if err := pv.signVote(chainID, vote); err != nil {
  222. return fmt.Errorf("error signing vote: %v", err)
  223. }
  224. return nil
  225. }
  226. // SignProposal signs a canonical representation of the proposal, along with
  227. // the chainID. Implements PrivValidator.
  228. func (pv *FilePV) SignProposal(chainID string, proposal *tmproto.Proposal) error {
  229. if err := pv.signProposal(chainID, proposal); err != nil {
  230. return fmt.Errorf("error signing proposal: %v", err)
  231. }
  232. return nil
  233. }
  234. // Save persists the FilePV to disk.
  235. func (pv *FilePV) Save() {
  236. pv.Key.Save()
  237. pv.LastSignState.Save()
  238. }
  239. // Reset resets all fields in the FilePV.
  240. // NOTE: Unsafe!
  241. func (pv *FilePV) Reset() {
  242. var sig []byte
  243. pv.LastSignState.Height = 0
  244. pv.LastSignState.Round = 0
  245. pv.LastSignState.Step = 0
  246. pv.LastSignState.Signature = sig
  247. pv.LastSignState.SignBytes = nil
  248. pv.Save()
  249. }
  250. // String returns a string representation of the FilePV.
  251. func (pv *FilePV) String() string {
  252. return fmt.Sprintf(
  253. "PrivValidator{%v LH:%v, LR:%v, LS:%v}",
  254. pv.GetAddress(),
  255. pv.LastSignState.Height,
  256. pv.LastSignState.Round,
  257. pv.LastSignState.Step,
  258. )
  259. }
  260. //------------------------------------------------------------------------------------
  261. // signVote checks if the vote is good to sign and sets the vote signature.
  262. // It may need to set the timestamp as well if the vote is otherwise the same as
  263. // a previously signed vote (ie. we crashed after signing but before the vote hit the WAL).
  264. func (pv *FilePV) signVote(chainID string, vote *tmproto.Vote) error {
  265. height, round, step := vote.Height, vote.Round, voteToStep(vote)
  266. lss := pv.LastSignState
  267. sameHRS, err := lss.CheckHRS(height, round, step)
  268. if err != nil {
  269. return err
  270. }
  271. signBytes := types.VoteSignBytes(chainID, vote)
  272. // We might crash before writing to the wal,
  273. // causing us to try to re-sign for the same HRS.
  274. // If signbytes are the same, use the last signature.
  275. // If they only differ by timestamp, use last timestamp and signature
  276. // Otherwise, return error
  277. if sameHRS {
  278. if bytes.Equal(signBytes, lss.SignBytes) {
  279. vote.Signature = lss.Signature
  280. } else if timestamp, ok := checkVotesOnlyDifferByTimestamp(lss.SignBytes, signBytes); ok {
  281. vote.Timestamp = timestamp
  282. vote.Signature = lss.Signature
  283. } else {
  284. err = fmt.Errorf("conflicting data")
  285. }
  286. return err
  287. }
  288. // It passed the checks. Sign the vote
  289. sig, err := pv.Key.PrivKey.Sign(signBytes)
  290. if err != nil {
  291. return err
  292. }
  293. pv.saveSigned(height, round, step, signBytes, sig)
  294. vote.Signature = sig
  295. return nil
  296. }
  297. // signProposal checks if the proposal is good to sign and sets the proposal signature.
  298. // It may need to set the timestamp as well if the proposal is otherwise the same as
  299. // a previously signed proposal ie. we crashed after signing but before the proposal hit the WAL).
  300. func (pv *FilePV) signProposal(chainID string, proposal *tmproto.Proposal) error {
  301. height, round, step := proposal.Height, proposal.Round, stepPropose
  302. lss := pv.LastSignState
  303. sameHRS, err := lss.CheckHRS(height, round, step)
  304. if err != nil {
  305. return err
  306. }
  307. signBytes := types.ProposalSignBytes(chainID, proposal)
  308. // We might crash before writing to the wal,
  309. // causing us to try to re-sign for the same HRS.
  310. // If signbytes are the same, use the last signature.
  311. // If they only differ by timestamp, use last timestamp and signature
  312. // Otherwise, return error
  313. if sameHRS {
  314. if bytes.Equal(signBytes, lss.SignBytes) {
  315. proposal.Signature = lss.Signature
  316. } else if timestamp, ok := checkProposalsOnlyDifferByTimestamp(lss.SignBytes, signBytes); ok {
  317. proposal.Timestamp = timestamp
  318. proposal.Signature = lss.Signature
  319. } else {
  320. err = fmt.Errorf("conflicting data")
  321. }
  322. return err
  323. }
  324. // It passed the checks. Sign the proposal
  325. sig, err := pv.Key.PrivKey.Sign(signBytes)
  326. if err != nil {
  327. return err
  328. }
  329. pv.saveSigned(height, round, step, signBytes, sig)
  330. proposal.Signature = sig
  331. return nil
  332. }
  333. // Persist height/round/step and signature
  334. func (pv *FilePV) saveSigned(height int64, round int32, step int8,
  335. signBytes []byte, sig []byte) {
  336. pv.LastSignState.Height = height
  337. pv.LastSignState.Round = round
  338. pv.LastSignState.Step = step
  339. pv.LastSignState.Signature = sig
  340. pv.LastSignState.SignBytes = signBytes
  341. pv.LastSignState.Save()
  342. }
  343. //-----------------------------------------------------------------------------------------
  344. // returns the timestamp from the lastSignBytes.
  345. // returns true if the only difference in the votes is their timestamp.
  346. func checkVotesOnlyDifferByTimestamp(lastSignBytes, newSignBytes []byte) (time.Time, bool) {
  347. var lastVote, newVote tmproto.CanonicalVote
  348. if err := protoio.UnmarshalDelimited(lastSignBytes, &lastVote); err != nil {
  349. panic(fmt.Sprintf("LastSignBytes cannot be unmarshalled into vote: %v", err))
  350. }
  351. if err := protoio.UnmarshalDelimited(newSignBytes, &newVote); err != nil {
  352. panic(fmt.Sprintf("signBytes cannot be unmarshalled into vote: %v", err))
  353. }
  354. lastTime := lastVote.Timestamp
  355. // set the times to the same value and check equality
  356. now := tmtime.Now()
  357. lastVote.Timestamp = now
  358. newVote.Timestamp = now
  359. return lastTime, proto.Equal(&newVote, &lastVote)
  360. }
  361. // returns the timestamp from the lastSignBytes.
  362. // returns true if the only difference in the proposals is their timestamp
  363. func checkProposalsOnlyDifferByTimestamp(lastSignBytes, newSignBytes []byte) (time.Time, bool) {
  364. var lastProposal, newProposal tmproto.CanonicalProposal
  365. if err := protoio.UnmarshalDelimited(lastSignBytes, &lastProposal); err != nil {
  366. panic(fmt.Sprintf("LastSignBytes cannot be unmarshalled into proposal: %v", err))
  367. }
  368. if err := protoio.UnmarshalDelimited(newSignBytes, &newProposal); err != nil {
  369. panic(fmt.Sprintf("signBytes cannot be unmarshalled into proposal: %v", err))
  370. }
  371. lastTime := lastProposal.Timestamp
  372. // set the times to the same value and check equality
  373. now := tmtime.Now()
  374. lastProposal.Timestamp = now
  375. newProposal.Timestamp = now
  376. return lastTime, proto.Equal(&newProposal, &lastProposal)
  377. }