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