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.

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