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