diff --git a/bindings/megapool/megapool-contract-v2.go b/bindings/megapool/megapool-contract-v2.go index 549a63a11..02f89c16c 100644 --- a/bindings/megapool/megapool-contract-v2.go +++ b/bindings/megapool/megapool-contract-v2.go @@ -19,7 +19,7 @@ type megapoolV2 struct { } const ( - megapoolV2EncodedAbi string = "eJztWktv2zgQ/isLn4M9tLs99OYmbhHATVMn3j0EgUFLY5sITaokZcco9r/vUC/rZYuyJEOtc0pkksN58ZsZDp9+DggXfLcWvhp8XBCm4GpAuedr/Hz6if+68ApuakiD5IQ97jwYfBz4+P3u7w+DqwEna/MDQUJc47fOTvjvqj4tTfFPkdJzMuErLIknBPskuDsB13eQeDIfNoCMmH1/fQFvYK5vuSOBqN9ZxN/ahveAVPRu6HmMNpFRS9+CrQ1h1CVayFv3zHL+E+88VIou+UWIegM/fPAvQ1SqlGCbi5B1xDsz6/t3FpLipDMJ+kr1ZVgUBaV8eQGSjoXzchEmfdDkMgSdctbQpn1MjyawJdJV14zgzO5l48KFYYvybQSOt0lQgl61Sc+TQgsH82si2iRra1dMF7Skc/9AeMlY8viOs4Nuud+UYHK9ixJtnCh8HZHHKUoTDV99TeaUURw2vsA9siNzlpJk4XNHU8EtuEuH8NnRGJ5iMMiJP/vcVdX8WTK3p+4Q5vgMyaAKXAxzkQ0yO1Ur2hyR/cpSX7E4E40oJE47/NaIjjlMhwmUKn1DYXuSO9R21sRab2Y6o5lOObXOijAGfAkmfWwTV1JbmPjXDWkXPAkOUuolIrph6dxP3qJaN0nBOjJQEiO7ob8EPcQJKTmuI3CqwJu0zkr1dNq5zHIW3RIhbzkvqMaNNsEiw5S5jOwLL1HJ2kfbjV49KomZ9Bimg71Q2JgonaSdfeMtqOD6aMs72CZshf2UHz6VsAYbBs+jvDtTu7muBFWRK5FkUoGleKhFloy2+qSi78GdZZ+4alSOdMbVBHBSv+LOVIG8Jh7VhPWJpdCjesZYT0C0tWQzLdItX4icRI5Ye4IjGlttyjAGhpmVAfDHwmVN0lmopGLiACi9T9CaUYlgqTYRLGKEotqaibkQbL9a5e6Ig9HKVZDrititovx7VNDUXHaPgcnwWZ9Nz4S0qarPq1ts5tmrJtNHsVuWv8A+tMrY9cNf2e0+EUa4kzM+TrJYHm5bPAVm9XPhrhMzR9/Rf0zMIh3fwj/gqSRLGJMdHso/8we1ACva97BC6yGqDLl7789fIHs9+gYvb/DyBi99hxcafmUhpkQnOw2p2seLj7tOD/cMmkox6bhc7UmUYelfqleuJFvCriW4iG6UsIqSJdi/PL2MhzrtNcwR9I739o6cmZmvYBQe8UdqXNLi0GUNsbf3fbmr1aDwgCGFaF+CLZGM40UofkM0mQihy80Qt09S9x2D/lw+V6PNbBt7KHIz8oSzOgWzZhIcdO4D61NqEpoudm33PbpXUth/u+VftkBt9FO4Mpo5pucj92uTm6M6JmJnMtBnipT2IewXMpRiIkggkcu1Vy3ondBnccba3VwZvF0u3Lq11sSRgEsKfYkm7wZaC+RxWtmB1BuQygyf/c6pyaOjApYI5t4Aw1RPwyE8qUcQg1cjgvWf88TbTb2lJG7r7+0KEi6kWLcj2llfs430yrypcIA2eiFdzk6h6NTlxVzLMmHlN8atlJ56CAblYtmAEMbTOXFeDj9TyHhYN3gS9HaTg9OLFlLMT9BMhYqeTdYF8tZvqau7WEDwXKBvmkoc0Y6xjnRlkTryTKOyRBlJQU9NeUlVtzlbruArBY5UNK9S9GnsWSCEDHHTKkt5ei7PU3IPyIKJNk/QZguAMV3T40neQkinlUdgz/8DcNqKAw==" + megapoolV2EncodedAbi string = "eJzsWl9z2jgQ/yo3fmbuAXp96BsN9CYzaS9NQu8hk2EWayGaCMmVVvyZTr77jY3BFjbYYMO5IY9g7e5v/2pX0uMvD6SSy6myxvs0BmGw5XEZWDLep8dfHpcMF8hSnwi1BPGwDND75Fkuqf3XR6/lSZiGf8BUWUleyyN3wWvrcF7Ep5jD6Wmz4CtOIFBKfFaS3SGzPrJkPc5QkvfaegsK9nBE19LXCOYtq/imfXiLEgQtu0EgeBUdSdsSsGYgOANS+prloDulnj/WkrvG8Im8CFV7+NOivQxVuTFKzC5C1748mVs77RKadtrnUnTB6TI8uuDE5eQCNL1R/stFuPSe4DIUHUhR0adNbI/ucA6amSsBfHoG3aRi2K1Rv5ki1HUy1EjPdfILtCLlK9ED1f0f/NrjhjQf2R3bi+PJ/RKHO8MyEQpBIJZxo+21PGUpZv/U8gwB4VdLMOKC0zKKBRnAEkYipcnYSp+4kiXQpbfw4c760Gk7AKOe+IuVzBTjKwku4e6D8K0AwluUjMtJ7ANHUrGhwxRJKHNjZT+DKCcqcdgEbfefSnzCZNrNINfoM47zIovXE6wbb7276YxuOiZr/WcQAuUE+wtOjptysZWvKykR4f53GtYMA40+ENbJvjbbstXo3Exs8ay7acHqROmIiffI0/CfIHV94ik9ruLilAgrtFmunY7LSxdZfEr0A4TFYkhO3aizWDigwsPIpmCJR9Ym+q6/CLiG0JYPqza/EQa7AUObtrNp2KIJrom+/IbzDazVfcpPyzVOUVJTjPctnN0Y02gKeiXYLMpAWn+qEVJorSaZ6Hu4n7Imoao0jpwM1R2OrWzWvjMwqK8g4ASiSZBWEdUwYA0porU1m2mVruVYbWnkq2mgJMpyQgWYuLMKC3i8A26JbpXiEu4DaChp0KpxicvSwUwYBspwKg1ipJRIqM3WGXH0tZAKt25FylFx+T0eaA4ku9UY4TyUEhdBuNsNnKcB5UjXA87BhLh9j1KObPsAexdV6NePH1xxn0GA9Lec//FDGfKV2GwWhNRPmbNOQ9r69MddSETrU/h7UhomeANLZenP7USN5STcyQYCm1hVupLd2tELLt/Ly3t5eS8vv1V54atfbonJwhstCVOzT7BO95hu9blhpSm3Ju3Xqz6NHEj/cnpmGuYgrjQylMRBFIwskfxOeye0TrsCuOIOezhSku2/29uTM0NrsL9K8QcehmRx+mw5YjjLeHHNIFp4CId7PpFAVmNZJk7gxVW8BwR3SlG+G+LFMnXe4bi34rFrxfQorjbD+TpCRwL7gfKfj6lZQ40+StpBnzKTIj5e1n3vcXojrS6Lr+Xfc+Rl7JM5Mhr64Z2Pzjk5OsRF4kwO+sIliGQL+40cZYSKGkhDMA2KFf2m6CzBePBtro7eLsf9Z23Y0vwDWGbuJXLZn8e3CbR1W3lajxyNLNzRlaVbrdS4kSjTjdDV+qq5h8AEl65di0M1P0ZrbD2qKrgeQ9I7/R4FtzqFTFtwtHIJuhlqE34+u6GrPGzL7FdKsB4KnKzu+cld9do6nKHEeSWGhz8ZW4sbBBMNLP/BWIU3nRkNx1pN61Ft5/5wCjP16Tl8t+Mjn1WxUT4cdziIwjl3IKhZp4HBGyA0NAgYUL5a2dzKFmoQYgT+SwwyVjoRw9wIc1K+4m6QCIneD2wSZ09NyQRkTjAeWlP244ku7LHgXtANgURO9H9NgPrjMUZPUppmqU0glgN2IlsVG2AonctwcpelMotLHh5hcONqUjHaCwwxzC0cCShTZOjj4GVJMuvDqYrPsECbsEJ12o9P+a3O1iPFaOGOUcepgsMx4g2f8v2DxFhpv5aHhk//DQDs3Fxe" ) // The decoded ABI for v2 megapools diff --git a/bindings/megapool/megapool-contract.go b/bindings/megapool/megapool-contract.go index 81f0de7f0..8abf0818d 100644 --- a/bindings/megapool/megapool-contract.go +++ b/bindings/megapool/megapool-contract.go @@ -30,6 +30,21 @@ type SlotProof struct { Witnesses [][32]byte `json:"witnesses"` } +type ProvedPendingDeposit struct { + Pubkey []byte `json:"pubkey"` + WithdrawalCredentials [32]byte `json:"withdrawalCredentials"` + AmountInGwei uint64 `json:"amountInGwei"` + Signature []byte `json:"signature"` + Slot uint64 `json:"slot"` +} + +type PendingDepositProof struct { + StateSlot uint64 `json:"stateSlot"` + DepositIndex uint64 `json:"depositIndex"` + Deposit ProvedPendingDeposit `json:"deposit"` + Witnesses [][32]byte `json:"witnesses"` +} + type ValidatorProof struct { ValidatorIndex *big.Int `json:"validatorIndex"` Validator ProvedValidator `json:"validator"` @@ -111,7 +126,7 @@ type megapoolV1 struct { } const ( - megapoolV1EncodedAbi string = "eJztWktv2zgQ/isLnY09pN0ccnPjtAiQZt0k7h6KwBiLY5sITbLk0I5Q9L8vJMuyZMmRFEuGUueYyBx+8+DHefDHLw+kksFCOetdTEFY7HlcakfWu/jxy+OS4TOy1CdCI0E8BBq9C89xSWf/nHs9T8Ii/AcslJPk9TzK/uB3r74s4gsskPSY/OArzkArJT4pye6QOR/Z9ve4REnRvm9fwQFO6Fr6BsH+ySr+0T4cogRBQV9rwQ/RkYyrAGsJgjMgZa7ZkfX8vtm5by2fyZNQdYA/HbrTUJVbq8TyJHS9kq259cNZBU0/nB1L0WdOp+HRZ05czk5A0xvlP52ES+8JTkPRkRQH+rSL6dEdrsAweymAL46gm1QM+w3qt1SEpkmBBmnepDxtFClfiQGoJsVW9euAWzJ84vZcLxlPvrzjeG9YbjcFrUUQJ9pez1OOYvGPPc8SEH51BBMuOAVRLEgNAUxESpOpkz5xJSugS1/h4xfv8BTAKCf+7CSz5fgqgttK90H4TgDhECXjchb7ILNTuaHDI7JdWRgrFc7EQRKSoO3/e5Cc8DDtF1Bo9CXH1avCoXawJt56d9MR3fSaU+vPQQiUMwzTxyZ5JbVFeP+1I5qhNugDYScZka1L525ii2vdJAVryUHJHdmO/BlS3yee0uMyJqcSvknbrNBOrzuXWWRxl+g7iJ0oKOeNJskiAypsRnYFS1yydtF3V8+aGwh/9LBOBzthsBuwlKSdXcMWVXBd9OUtrhJY63nKT8cNLrAKwOMY7zas3RgzaEtyJUh+lIO0+dQgpNBaXTLRt6hn2SVUB5UjraG6w6mT3bp3RhbNJWhOILoEaR1RHQPWERJtLNlMq3Qtp2pHI18ttJIoq20qwMaZVUjgD7lmTTJZKJUS3gNoaZugHSYlpqXaQhhqZTlVBjFRSmxX250ecfS1dBXuTEWqreLyW1zQ1Fw2NBjhrA9Th1fayNbHyvLDvOqmycxRqi3bbWDvWxX69fxjdrtPIED6O84//1hl+Xrb/CkIVz/mep2WjPPpr7twEW268PekDMzwBgLl6O/dg5qjFXJaYBdZpS/Z0E2eMHinl3d6eaeXN0UvfP1XlmIKbBIQpmofvTnulP7cMWoq5KSX9WpOowyk/zjNmYEViEuDDCVxECUlS7R/cXq5+dTqrGGiJHt5tvfCmRk7i1frI/7Aw5CscOiyjtj6e1gcajUk3POZBHIGqwrJBF7M4gMguFOKit2wGZ+k+h0daj6Xs814tYnQicArrfz5azhrbNBHSXvWp8ykiE+Dpuce7RtpPX+7ll9WyKvYJ9cyGvvhzMcUdI7quEgcyUGfuQSxvcLekKOsUFECaQkWulzRW0VHCcba01wTvV3Odd0aG+IY1BDk5hKHvBto7CLfpJUtaL1EY8PPR+85HfLoKMclSrABCpytZ7CFfFJPoMTVQQLrP+fZbDfSMwOs8fd2OQ2nRi2aUe2or9muaB6+qfCRH/RCuhhOruik4mKuYZ1GFm+A0NJIM9jzjqsKCYEQE/Cf9j9TyERYa6Pw1MHpxAhpgycapmLJzCYbArveb2iqO51i9Fyga5ZKArEasJZsVSF1lJlBZYExkoKeh+Ult+3mbDsFXyFxpG7zMkO/Dl4FhjBr3vR+P/4PdOc9cw==" + megapoolV1EncodedAbi string = "eJzsWktv4kgQ/isrn9EeyGwOuTGBWUXKZDNJmD2MIlS4C9JK0+3pruahUf77ysZgNzbYYMN6Qo7grqqv3tWPH788kEouJsoa72oEwmDL4zKwZLyrH788LhnOkaU+EWoJ4mkRoHflWS6p/del1/IkTMI/YKKsJK/lkbvgrbU/L+ITzOH0vF7wFccQKCU+K8kekFkfWbIepyjJe2u9BwW7OKQb6WsE855VfNc+vEcJghadIBC8io6kbQlYUxCcASl9w3LQHVPP7yvJHWP4WJ6Fql38adGeh6rcGCWmZ6FrTx7NrRftEppetE+l6JzTeXh0zonL8Rloeqv817Nw6SPBeSjal6KiT5s4Hj3gDDQz1wL45AS6ScWwU6N+U0Wo62SokV7q5BdoRcpXoguq8z/4tcsNaT60W9qL48ndEgdbwzIRCkEgFvGg7bU8ZSlm/9zyDAHhV0sw5ILTIooFGcAChiKlychKn7iSJdClW/hga324aDsAo5n4i5XMFOMrCS7h7oPwrQDCe5SMy3HsA0dSsaHDFEkoc2NlN4MoJypxWAdt559KfMJk2s4g1+hTjrMii9cTrGtvfbjphG46JGv9FxAC5Rh7c06Om3Kxla8rKRFh/zsOa4aBRh8I62Rfm23ZcuvcTGzxXnc9gtWJ0hET98jj8B8jdXziKT2u4+KUCCu0Wa6dDstLF1l8SvQdhMViSE7dqLNYOKDCw8imYIm3rE30XW8ecA2hLZ+WY34jDHYLhtZjZ9OwRTu4JvryDmdrWMv7lJ+Wa5ygpKYY7y7cuzGm0RTMSrBelIG0+lQjpNBaTTLRt7CfsiahqrQdORqqBxxZ2ay+0zeoryHgBKJJkJYR1TBgDSmitQ2baZVu5EhtaOSrSaAkynJCBZh4sgoLeNwBN0S3SnEJ+wAaSga0alzisrQ3E4aBMpxKgxgqJRJqs3FGHH0tpMKNW5FyVFx+izc0e5Lda4xw7kuJ8yDsdn3naUA50tUGZ29C3LxHKUe2eYC9jSr06+UnV9xnECD9DedffipDvhSbzYKQ+jlz1mlIW5/+eAiJaHUK/0hKwxhvYaEs/bmZqLGchDvZQGATq0pHsns7fMXFR3n5KC8f5eW3Ki98+cstMVl4wwVhau8TrNI9plt+blhpyq1Ju/WqTyMH0r+cXpiGGYhrjQwlcRAFW5ZI/kV7K7SLdgVwxRP2YKgk2323tyNnBtZgb5niTzwMyeL02XDEYJrx4opBtHAfDo98LIGsxrJMnMCLq3gXCB6Uonw3xItl6rzDcW/FY9eK6VFcbQazVYQOBfYC5b8cUrMGGn2UtIU+ZSZFfLSo+97j+EZaXhbfyL9nyMvYJ3NkNPDDOx+dc3K0j4vEiRz0hUsQSQv7jRxlhIoGSEMwCYoVvVN0kmDc+zZXR2+X4/mzNmxp/gEsMvcSuexP49sE2mqsPK5HDkYWdnRl6V4rNWokyvQgdL26au4iMMGla9fiUM2P0RpHj6oKrrYh6U6/Q8GNSSEzFhysXIJuitqEn09u6CoP2zL9SgnWRYHj5T0/uaveWvszlDirxHD/J2Mrcf1grIHlPxir8KYzo+FIq0k9qm3tD8cwU49ewnc7PvJpFRvlw3E3B1E4524Iatapb/AWCA31AwaUr1Y2t7KFGoQYgv8ag4yVTsQwN8KclK/YDRIh0fuBdeLsqCmZgMwJxn1rym480YU9FtwLuiGQyIn+rwlQbzTC6ElK0yy1DsRywI5kq2IDDKRzGU7uslRmccnDIwxuXE0qRnuBIQa5hSMBZYoMfRi8LElmvUYf+RS9t+f/BgA++g/O" ) // The decoded ABI for megapools @@ -629,6 +644,38 @@ func (mp *megapoolV1) GetMegapoolPubkeys(opts *bind.CallOpts) ([]rptypes.Validat return pubkeys, nil } +// Fixed challenge deadline stored for this validator, or zero when none was snapshotted +func (mp *megapoolV1) GetValidatorChallengeDeadline(validatorId uint32, opts *bind.CallOpts) (*big.Int, error) { + deadline := new(*big.Int) + if err := mp.Contract.Call(opts, deadline, "getValidatorChallengeDeadline", validatorId); err != nil { + return nil, fmt.Errorf("error getting megapool %s validator %d challenge deadline: %w", mp.Address.Hex(), validatorId, err) + } + return *deadline, nil +} + +// Signature retained from the validator's initial deposit. Empty for legacy prestakes. +func (mp *megapoolV1) GetValidatorPrestakeSignature(validatorId uint32, opts *bind.CallOpts) ([]byte, error) { + signature := new([]byte) + if err := mp.Contract.Call(opts, signature, "getValidatorPrestakeSignature", validatorId); err != nil { + return nil, fmt.Errorf("error getting megapool %s validator %d prestake signature: %w", mp.Address.Hex(), validatorId, err) + } + return *signature, nil +} + +// Estimate the gas required to stake a prestaked validator after its challenge period without a beacon state proof +func (mp *megapoolV1) EstimateStakeWithoutProofGas(validatorId uint32, opts *bind.TransactOpts) (gaslimit.Limits, error) { + return mp.Contract.GetTransactionGasInfo(opts, "stakeWithoutProof", validatorId) +} + +// Stake a prestaked validator after its challenge period without a beacon state proof +func (mp *megapoolV1) StakeWithoutProof(validatorId uint32, opts *bind.TransactOpts) (common.Hash, error) { + tx, err := mp.Contract.Transact(opts, "stakeWithoutProof", validatorId) + if err != nil { + return common.Hash{}, fmt.Errorf("error staking validator ID %d without a proof: %w", validatorId, err) + } + return tx.Hash(), nil +} + // Create a megapool contract directly from its ABI func createMegapoolContractFromAbi(rp *rocketpool.RocketPool, address common.Address, abi *abi.ABI) (*rocketpool.Contract, error) { // Create and return diff --git a/bindings/megapool/megapool-interface.go b/bindings/megapool/megapool-interface.go index 42026e55e..4af598de4 100644 --- a/bindings/megapool/megapool-interface.go +++ b/bindings/megapool/megapool-interface.go @@ -23,6 +23,8 @@ type Megapool interface { GetValidatorInfo(validatorId uint32, opts *bind.CallOpts) (ValidatorInfo, error) GetValidatorPubkey(validatorId uint32, opts *bind.CallOpts) (rptypes.ValidatorPubkey, error) GetValidatorInfoAndPubkey(validatorId uint32, opts *bind.CallOpts) (ValidatorInfoWithPubkey, error) + GetValidatorChallengeDeadline(validatorId uint32, opts *bind.CallOpts) (*big.Int, error) + GetValidatorPrestakeSignature(validatorId uint32, opts *bind.CallOpts) ([]byte, error) GetLastDistributionTime(opts *bind.CallOpts) (uint64, error) GetAssignedValue(opts *bind.CallOpts) (*big.Int, error) GetDebt(opts *bind.CallOpts) (*big.Int, error) @@ -40,6 +42,8 @@ type Megapool interface { Distribute(opts *bind.TransactOpts) (common.Hash, error) EstimateDissolveValidatorGas(validatorId uint32, opts *bind.TransactOpts) (gaslimit.Limits, error) DissolveValidator(validatorId uint32, opts *bind.TransactOpts) (common.Hash, error) + EstimateStakeWithoutProofGas(validatorId uint32, opts *bind.TransactOpts) (gaslimit.Limits, error) + StakeWithoutProof(validatorId uint32, opts *bind.TransactOpts) (common.Hash, error) EstimateClaimRefundGas(opts *bind.TransactOpts) (gaslimit.Limits, error) ClaimRefund(opts *bind.TransactOpts) (common.Hash, error) EstimateRepayDebtGas(opts *bind.TransactOpts) (gaslimit.Limits, error) diff --git a/bindings/megapool/megapool-manager.go b/bindings/megapool/megapool-manager.go index 88dcbfa58..692528bee 100644 --- a/bindings/megapool/megapool-manager.go +++ b/bindings/megapool/megapool-manager.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" @@ -119,6 +120,122 @@ func GetValidatorInfo(rp *rocketpool.RocketPool, index uint32, opts *bind.CallOp return *validator, nil } +// PrestakedValidatorIndices is one page of RocketMegapoolManager.getPrestakedValidatorIndices. +type PrestakedValidatorIndices struct { + Indices []*big.Int `abi:"indices"` + NextIndex *big.Int `abi:"nextIndex"` + FailedIndices []*big.Int `abi:"failedIndices"` +} + +// ValidatorPrestakeInfo is the RocketMegapoolManager.getValidatorPrestakeInfo return value. +type ValidatorPrestakeInfo struct { + Pubkey []byte `abi:"pubkey"` + ValidatorInfo ValidatorInfo `abi:"validatorInfo"` + MegapoolAddress common.Address `abi:"megapool"` + ValidatorId uint32 `abi:"validatorId"` + Signature []byte `abi:"signature"` + ChallengeDeadline *big.Int `abi:"challengeDeadline"` +} + +// GetPrestakedValidatorIndices returns prestaked global indices in [offset, offset+limit). +func GetPrestakedValidatorIndices(rp *rocketpool.RocketPool, offset, limit *big.Int, opts *bind.CallOpts) (PrestakedValidatorIndices, error) { + megapoolManager, err := getRocketMegapoolManager(rp, opts) + if err != nil { + return PrestakedValidatorIndices{}, err + } + page := new(PrestakedValidatorIndices) + if err := megapoolManager.Call(opts, page, "getPrestakedValidatorIndices", offset, limit); err != nil { + return PrestakedValidatorIndices{}, fmt.Errorf("error getting prestaked validator indices: %w", err) + } + return *page, nil +} + +// GetValidatorPrestakeInfo returns the prestake watcher data for one global validator index. +func GetValidatorPrestakeInfo(rp *rocketpool.RocketPool, index *big.Int, opts *bind.CallOpts) (ValidatorPrestakeInfo, error) { + megapoolManager, err := getRocketMegapoolManager(rp, opts) + if err != nil { + return ValidatorPrestakeInfo{}, err + } + callData, err := megapoolManager.ABI.Pack("getValidatorPrestakeInfo", index) + if err != nil { + return ValidatorPrestakeInfo{}, fmt.Errorf("error creating calldata for getValidatorPrestakeInfo: %w", err) + } + response, err := megapoolManager.Client.CallContract(context.Background(), ethereum.CallMsg{ + To: megapoolManager.Address, + Data: callData, + }, callBlockNumber(opts)) + if err != nil { + return ValidatorPrestakeInfo{}, fmt.Errorf("error calling getValidatorPrestakeInfo: %w", err) + } + info, err := unpackValidatorPrestakeInfo(megapoolManager.ABI, response) + if err != nil { + return ValidatorPrestakeInfo{}, fmt.Errorf("error unpacking getValidatorPrestakeInfo response: %w", err) + } + return info, nil +} + +func unpackValidatorPrestakeInfo(contractABI *abi.ABI, data []byte) (ValidatorPrestakeInfo, error) { + var info ValidatorPrestakeInfo + if err := contractABI.UnpackIntoInterface(&info, "getValidatorPrestakeInfo", data); err != nil { + return ValidatorPrestakeInfo{}, err + } + if info.ChallengeDeadline == nil { + return ValidatorPrestakeInfo{}, fmt.Errorf("challengeDeadline is nil") + } + return info, nil +} + +func callBlockNumber(opts *bind.CallOpts) *big.Int { + if opts == nil { + return nil + } + return opts.BlockNumber +} + +// Estimate the gas of ChallengeInvalidSignature +func EstimateChallengeInvalidSignatureGas(rp *rocketpool.RocketPool, megapoolAddress common.Address, validatorId uint32, opts *bind.TransactOpts) (gaslimit.Limits, error) { + megapoolManager, err := getRocketMegapoolManager(rp, nil) + if err != nil { + return gaslimit.Limits{}, err + } + return megapoolManager.GetTransactionGasInfo(opts, "challengeInvalidSignature", megapoolAddress, validatorId) +} + +// Estimate the gas of DissolvePendingDeposit +func EstimateDissolvePendingDepositGas(rp *rocketpool.RocketPool, megapoolAddress common.Address, validatorId uint32, slotTimestamp uint64, proofVersion *big.Int, proofData []byte, opts *bind.TransactOpts) (gaslimit.Limits, error) { + megapoolManager, err := getRocketMegapoolManager(rp, nil) + if err != nil { + return gaslimit.Limits{}, err + } + return megapoolManager.GetTransactionGasInfo(opts, "dissolvePendingDeposit", megapoolAddress, validatorId, slotTimestamp, proofVersion, proofData) +} + +// Dissolve a prestaked validator whose pending deposit is signed to withdrawal credentials other than its megapool +func DissolvePendingDeposit(rp *rocketpool.RocketPool, megapoolAddress common.Address, validatorId uint32, slotTimestamp uint64, proofVersion *big.Int, proofData []byte, opts *bind.TransactOpts) (*types.Transaction, error) { + megapoolManager, err := getRocketMegapoolManager(rp, nil) + if err != nil { + return nil, err + } + tx, err := megapoolManager.Transact(opts, "dissolvePendingDeposit", megapoolAddress, validatorId, slotTimestamp, proofVersion, proofData) + if err != nil { + return nil, fmt.Errorf("error dissolving pending deposit for megapool %s validator %d: %w", megapoolAddress.Hex(), validatorId, err) + } + return tx, nil +} + +// Challenge a prestaked validator whose retained deposit signature is invalid +func ChallengeInvalidSignature(rp *rocketpool.RocketPool, megapoolAddress common.Address, validatorId uint32, opts *bind.TransactOpts) (*types.Transaction, error) { + megapoolManager, err := getRocketMegapoolManager(rp, nil) + if err != nil { + return nil, err + } + tx, err := megapoolManager.Transact(opts, "challengeInvalidSignature", megapoolAddress, validatorId) + if err != nil { + return nil, fmt.Errorf("error challenging invalid prestake signature for megapool %s validator %d: %w", megapoolAddress.Hex(), validatorId, err) + } + return tx, nil +} + // Estimate the gas of Stake func EstimateStakeGas(rp *rocketpool.RocketPool, megapoolAddress common.Address, validatorId uint32, slotTimestamp uint64, proofVersion *big.Int, proofData []byte, opts *bind.TransactOpts) (gaslimit.Limits, error) { megapoolManager, err := getRocketMegapoolManager(rp, nil) diff --git a/bindings/megapool/megapool-manager_test.go b/bindings/megapool/megapool-manager_test.go new file mode 100644 index 000000000..d5e90fd51 --- /dev/null +++ b/bindings/megapool/megapool-manager_test.go @@ -0,0 +1,131 @@ +package megapool + +import ( + "math/big" + "strings" + "testing" + + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" +) + +const prestakeWatcherABI = `[ + { + "name": "getPrestakedValidatorIndices", + "type": "function", + "stateMutability": "view", + "inputs": [ + {"name": "_offset", "type": "uint256"}, + {"name": "_limit", "type": "uint256"} + ], + "outputs": [ + {"name": "indices", "type": "uint256[]"}, + {"name": "nextIndex", "type": "uint256"}, + {"name": "failedIndices", "type": "uint256[]"} + ] + }, + { + "name": "getValidatorPrestakeInfo", + "type": "function", + "stateMutability": "view", + "inputs": [ + {"name": "_index", "type": "uint256"} + ], + "outputs": [ + {"name": "pubkey", "type": "bytes"}, + {"name": "validatorInfo", "type": "tuple", "components": [ + {"name": "lastAssignmentTime", "type": "uint32"}, + {"name": "lastRequestedValue", "type": "uint32"}, + {"name": "lastRequestedBond", "type": "uint32"}, + {"name": "depositValue", "type": "uint32"}, + {"name": "staked", "type": "bool"}, + {"name": "exited", "type": "bool"}, + {"name": "inQueue", "type": "bool"}, + {"name": "inPrestake", "type": "bool"}, + {"name": "expressUsed", "type": "bool"}, + {"name": "dissolved", "type": "bool"}, + {"name": "exiting", "type": "bool"}, + {"name": "locked", "type": "bool"}, + {"name": "exitBalance", "type": "uint64"}, + {"name": "lockedTime", "type": "uint64"} + ]}, + {"name": "megapool", "type": "address"}, + {"name": "validatorId", "type": "uint32"}, + {"name": "signature", "type": "bytes"}, + {"name": "challengeDeadline", "type": "uint256"} + ] + } +]` + +func TestUnpackPrestakedValidatorIndices(t *testing.T) { + parsed := mustPrestakeABI(t) + indices := []*big.Int{big.NewInt(4), big.NewInt(9)} + next := big.NewInt(12) + failed := []*big.Int{big.NewInt(7)} + packed, err := parsed.Methods["getPrestakedValidatorIndices"].Outputs.Pack(indices, next, failed) + if err != nil { + t.Fatal(err) + } + var page PrestakedValidatorIndices + if err := parsed.UnpackIntoInterface(&page, "getPrestakedValidatorIndices", packed); err != nil { + t.Fatal(err) + } + if len(page.Indices) != 2 || page.Indices[0].Cmp(indices[0]) != 0 || page.Indices[1].Cmp(indices[1]) != 0 { + t.Fatalf("indices = %v", page.Indices) + } + if page.NextIndex.Cmp(next) != 0 { + t.Fatalf("nextIndex = %s", page.NextIndex) + } + if len(page.FailedIndices) != 1 || page.FailedIndices[0].Cmp(failed[0]) != 0 { + t.Fatalf("failedIndices = %v", page.FailedIndices) + } +} + +func TestUnpackValidatorPrestakeInfo(t *testing.T) { + parsed := mustPrestakeABI(t) + pubkey := make([]byte, 48) + pubkey[0] = 0xab + signature := make([]byte, 96) + signature[0] = 0xcd + megapoolAddress := common.HexToAddress("0x1111111111111111111111111111111111111111") + deadline := big.NewInt(43200) + info := ValidatorInfo{ + LastAssignmentTime: 10, + LastRequestedValue: 32000, + LastRequestedBond: 4000, + DepositValue: 1000, + InPrestake: true, + ExitBalance: 32, + } + packed, err := parsed.Methods["getValidatorPrestakeInfo"].Outputs.Pack( + pubkey, info, megapoolAddress, uint32(3), signature, deadline, + ) + if err != nil { + t.Fatal(err) + } + got, err := unpackValidatorPrestakeInfo(&parsed, packed) + if err != nil { + t.Fatal(err) + } + if got.Pubkey[0] != 0xab || got.Signature[0] != 0xcd { + t.Fatalf("pubkey/signature not preserved: %x %x", got.Pubkey, got.Signature) + } + if got.MegapoolAddress != megapoolAddress || got.ValidatorId != 3 { + t.Fatalf("identity = %s %d", got.MegapoolAddress.Hex(), got.ValidatorId) + } + if !got.ValidatorInfo.InPrestake || got.ValidatorInfo.LastAssignmentTime != 10 || got.ValidatorInfo.LastRequestedBond != 4000 { + t.Fatalf("validator info = %+v", got.ValidatorInfo) + } + if got.ChallengeDeadline.Cmp(deadline) != 0 { + t.Fatalf("deadline = %s", got.ChallengeDeadline) + } +} + +func mustPrestakeABI(t *testing.T) abi.ABI { + t.Helper() + parsed, err := abi.JSON(strings.NewReader(prestakeWatcherABI)) + if err != nil { + t.Fatal(err) + } + return parsed +} diff --git a/bindings/megapool/proof-bundle.go b/bindings/megapool/proof-bundle.go index c991b78cc..575048532 100644 --- a/bindings/megapool/proof-bundle.go +++ b/bindings/megapool/proof-bundle.go @@ -12,11 +12,12 @@ import ( // Proof versions accepted by BeaconStateVerifier var ( - ValidatorProofVersion1 = big.NewInt(1) - SlotProofVersion1 = big.NewInt(1) - ParticipationProofVersion1 = big.NewInt(1) - FinalBalanceProofVersion1 = big.NewInt(1) - FinalBalanceProofVersion2 = big.NewInt(2) + ValidatorProofVersion1 = big.NewInt(1) + SlotProofVersion1 = big.NewInt(1) + ParticipationProofVersion1 = big.NewInt(1) + FinalBalanceProofVersion1 = big.NewInt(1) + FinalBalanceProofVersion2 = big.NewInt(2) + PendingDepositProofVersion1 = big.NewInt(1) ) type ValidatorProofBundleV1 struct { @@ -34,6 +35,11 @@ type ParticipationProofBundleV1 struct { SlotProof SlotProof `json:"slotProof"` } +type PendingDepositProofBundleV1 struct { + PendingDepositProof PendingDepositProof `json:"pendingDepositProof"` + SlotProof SlotProof `json:"slotProof"` +} + type FinalBalanceProofBundleV1 struct { WithdrawalProof WithdrawalProof `json:"withdrawalProof"` ValidatorProof ValidatorProof `json:"validatorProof"` @@ -114,6 +120,19 @@ var ( {Name: "balanceChunk", Type: "bytes32"}, {Name: "witnesses", Type: "bytes32[]"}, } + pendingDepositComponents = []abi.ArgumentMarshaling{ + {Name: "pubkey", Type: "bytes"}, + {Name: "withdrawalCredentials", Type: "bytes32"}, + {Name: "amountInGwei", Type: "uint64"}, + {Name: "signature", Type: "bytes"}, + {Name: "slot", Type: "uint64"}, + } + pendingDepositProofComponents = []abi.ArgumentMarshaling{ + {Name: "stateSlot", Type: "uint64"}, + {Name: "depositIndex", Type: "uint64"}, + {Name: "deposit", Type: "tuple", Components: pendingDepositComponents}, + {Name: "witnesses", Type: "bytes32[]"}, + } ) func EncodeValidatorProofBundleV1(validatorProof ValidatorProof, slotProof SlotProof) ([]byte, error) { @@ -132,6 +151,16 @@ func EncodeSlotProofBundleV1(slotProof SlotProof) ([]byte, error) { }, SlotProofBundleV1{SlotProof: slotProof}) } +func EncodePendingDepositProofBundleV1(pendingDepositProof PendingDepositProof, slotProof SlotProof) ([]byte, error) { + return encodeTuple([]abi.ArgumentMarshaling{ + {Name: "pendingDepositProof", Type: "tuple", Components: pendingDepositProofComponents}, + {Name: "slotProof", Type: "tuple", Components: slotProofComponents}, + }, PendingDepositProofBundleV1{ + PendingDepositProof: pendingDepositProof, + SlotProof: slotProof, + }) +} + func EncodeParticipationProofBundleV1(validatorProof ValidatorProof, participationProof ParticipationProof, slotProof SlotProof) ([]byte, error) { return encodeTuple([]abi.ArgumentMarshaling{ {Name: "validatorProof", Type: "tuple", Components: validatorProofComponents}, diff --git a/bindings/megapool/proof-bundle_test.go b/bindings/megapool/proof-bundle_test.go index dcc1793b2..453b55ae1 100644 --- a/bindings/megapool/proof-bundle_test.go +++ b/bindings/megapool/proof-bundle_test.go @@ -53,6 +53,27 @@ func TestEncodeValidatorProofBundleV1(t *testing.T) { } } +func TestEncodePendingDepositProofBundleV1(t *testing.T) { + encoded, err := EncodePendingDepositProofBundleV1(PendingDepositProof{ + StateSlot: 10, + DepositIndex: 2, + Deposit: ProvedPendingDeposit{ + Pubkey: make([]byte, 48), + WithdrawalCredentials: [32]byte{0x01}, + AmountInGwei: 2_000_000_000, + Signature: make([]byte, 96), + Slot: 8, + }, + Witnesses: [][32]byte{{0x11}, {0x22}}, + }, sampleSlotProof()) + if err != nil { + t.Fatalf("encode: %v", err) + } + if len(encoded) == 0 { + t.Fatal("expected non-empty encoding") + } +} + func TestEncodeFinalBalanceProofBundleV1(t *testing.T) { encoded, err := EncodeFinalBalanceProofBundleV1(sampleWithdrawalProof(), sampleValidatorProof(), sampleSlotProof()) if err != nil { diff --git a/bindings/megapool/proofless_stake_abi_test.go b/bindings/megapool/proofless_stake_abi_test.go new file mode 100644 index 000000000..557d43914 --- /dev/null +++ b/bindings/megapool/proofless_stake_abi_test.go @@ -0,0 +1,53 @@ +package megapool + +import ( + "bytes" + "testing" + + "github.com/ethereum/go-ethereum/crypto" + + "github.com/rocket-pool/smartnode/bindings/rocketpool" +) + +func TestMegapoolABIIncludesProoflessStake(t *testing.T) { + signatures := []string{ + "stakeWithoutProof(uint32)", + "getValidatorChallengeDeadline(uint32)", + "getValidatorPrestakeSignature(uint32)", + } + for _, encoded := range []string{megapoolV1EncodedAbi, megapoolV2EncodedAbi} { + parsed, err := rocketpool.DecodeAbi(encoded) + if err != nil { + t.Fatal(err) + } + for _, signature := range signatures { + name := signature[:bytes.IndexByte([]byte(signature), '(')] + method, ok := parsed.Methods[name] + if !ok { + t.Fatalf("missing %s", name) + } + want := crypto.Keccak256([]byte(signature))[:4] + if !bytes.Equal(method.ID, want) { + t.Fatalf("%s selector = %x, want %x", signature, method.ID, want) + } + } + packed, err := parsed.Pack("stakeWithoutProof", uint32(4)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(packed[:4], crypto.Keccak256([]byte("stakeWithoutProof(uint32)"))[:4]) { + t.Fatalf("packed selector = %x", packed[:4]) + } + var arg [32]byte + arg[31] = 4 + if !bytes.Equal(packed[4:], arg[:]) { + t.Fatalf("packed validator id = %x", packed[4:]) + } + if _, err := parsed.Pack("getValidatorChallengeDeadline", uint32(1)); err != nil { + t.Fatal(err) + } + if _, err := parsed.Pack("getValidatorPrestakeSignature", uint32(1)); err != nil { + t.Fatal(err) + } + } +} diff --git a/bindings/settings/protocol/megapool.go b/bindings/settings/protocol/megapool.go index 8d7489e98..896f26923 100644 --- a/bindings/settings/protocol/megapool.go +++ b/bindings/settings/protocol/megapool.go @@ -4,6 +4,7 @@ import ( "fmt" "math/big" "sync" + "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" @@ -26,6 +27,8 @@ const ( MegapoolUserDistributeDelayShortfallPath string = "user.distribute.delay.shortfall" MegapoolPenaltyThreshold string = "megapool.penalty.threshold" MegapoolExitDeficitPath string = "megapool.exit.deficit" + MegapoolPrestakeChallengePeriodPath string = "megapool.prestake.challenge.period" + MegapoolStakeWithoutProofEnabledPath string = "megapool.stake.without.proof.enabled" ) // Get the deficit threshold in wei for permissionless megapool exits (Saturn 2). @@ -48,6 +51,46 @@ func EstimateProposeMegapoolExitDeficitGas(rp *rocketpool.RocketPool, value *big return protocol.EstimateProposeSetUintGas(rp, fmt.Sprintf("set %s", MegapoolExitDeficitPath), MegapoolSettingsContractName, MegapoolExitDeficitPath, value, blockNumber, treeNodes, opts) } +// How long a new prestake can be challenged before staking without a state proof is allowed (stored on-chain in seconds) +func GetPrestakeChallengePeriod(rp *rocketpool.RocketPool, opts *bind.CallOpts) (time.Duration, error) { + megapoolSettingsContract, err := getMegapoolSettingsContract(rp, opts) + if err != nil { + return 0, err + } + value := new(*big.Int) + if err := megapoolSettingsContract.Call(opts, value, "getPrestakeChallengePeriod"); err != nil { + return 0, fmt.Errorf("error getting megapool prestake challenge period value: %w", err) + } + return time.Duration((*value).Int64()) * time.Second, nil +} + +// Proofless staking is only accepted by the megapool delegate when this is true. +func GetStakeWithoutProofEnabled(rp *rocketpool.RocketPool, opts *bind.CallOpts) (bool, error) { + megapoolSettingsContract, err := getMegapoolSettingsContract(rp, opts) + if err != nil { + return false, err + } + value := new(bool) + if err := megapoolSettingsContract.Call(opts, value, "getStakeWithoutProofEnabled"); err != nil { + return false, fmt.Errorf("error getting megapool stake without proof enabled: %w", err) + } + return *value, nil +} + +func ProposeStakeWithoutProofEnabled(rp *rocketpool.RocketPool, value bool, blockNumber uint32, treeNodes []types.VotingTreeNode, opts *bind.TransactOpts) (uint64, common.Hash, error) { + return protocol.ProposeSetBool(rp, fmt.Sprintf("set %s", MegapoolStakeWithoutProofEnabledPath), MegapoolSettingsContractName, MegapoolStakeWithoutProofEnabledPath, value, blockNumber, treeNodes, opts) +} +func EstimateProposeStakeWithoutProofEnabledGas(rp *rocketpool.RocketPool, value bool, blockNumber uint32, treeNodes []types.VotingTreeNode, opts *bind.TransactOpts) (gaslimit.Limits, error) { + return protocol.EstimateProposeSetBoolGas(rp, fmt.Sprintf("set %s", MegapoolStakeWithoutProofEnabledPath), MegapoolSettingsContractName, MegapoolStakeWithoutProofEnabledPath, value, blockNumber, treeNodes, opts) +} + +func ProposePrestakeChallengePeriod(rp *rocketpool.RocketPool, value *big.Int, blockNumber uint32, treeNodes []types.VotingTreeNode, opts *bind.TransactOpts) (uint64, common.Hash, error) { + return protocol.ProposeSetUint(rp, fmt.Sprintf("set %s", MegapoolPrestakeChallengePeriodPath), MegapoolSettingsContractName, MegapoolPrestakeChallengePeriodPath, value, blockNumber, treeNodes, opts) +} +func EstimateProposePrestakeChallengePeriod(rp *rocketpool.RocketPool, value *big.Int, blockNumber uint32, treeNodes []types.VotingTreeNode, opts *bind.TransactOpts) (gaslimit.Limits, error) { + return protocol.EstimateProposeSetUintGas(rp, fmt.Sprintf("set %s", MegapoolPrestakeChallengePeriodPath), MegapoolSettingsContractName, MegapoolPrestakeChallengePeriodPath, value, blockNumber, treeNodes, opts) +} + // How long after an assignment a watcher must wait to dissolve a megapool validator func GetMegapoolTimeBeforeDissolve(rp *rocketpool.RocketPool, opts *bind.CallOpts) (uint64, error) { megapoolSettingsContract, err := getMegapoolSettingsContract(rp, opts) diff --git a/bindings/settings/protocol/setting-types.go b/bindings/settings/protocol/setting-types.go index 78e11c939..c59bdc606 100644 --- a/bindings/settings/protocol/setting-types.go +++ b/bindings/settings/protocol/setting-types.go @@ -139,6 +139,8 @@ var pdaoSettingKinds = map[string]map[string]settingKind{ MegapoolUserDistributeDelayShortfallPath: settingKindUint256, MegapoolPenaltyThreshold: settingKindUint256, MegapoolExitDeficitPath: settingKindUint256, + MegapoolPrestakeChallengePeriodPath: settingKindUint256, + MegapoolStakeWithoutProofEnabledPath: settingKindBool, }, } diff --git a/bindings/settings/security/megapool.go b/bindings/settings/security/megapool.go new file mode 100644 index 000000000..3534597ec --- /dev/null +++ b/bindings/settings/security/megapool.go @@ -0,0 +1,25 @@ +package security + +import ( + "fmt" + + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + + "github.com/rocket-pool/smartnode/bindings/dao/security" + "github.com/rocket-pool/smartnode/bindings/rocketpool" + psettings "github.com/rocket-pool/smartnode/bindings/settings/protocol" + "github.com/rocket-pool/smartnode/bindings/transactions/gaslimit" +) + +const ( + megapoolNamespace string = "megapool" +) + +// Proofless staking currently enabled +func ProposeStakeWithoutProofEnabled(rp *rocketpool.RocketPool, value bool, opts *bind.TransactOpts) (uint64, common.Hash, error) { + return security.ProposeSetBool(rp, fmt.Sprintf("set %s", psettings.MegapoolStakeWithoutProofEnabledPath), megapoolNamespace, psettings.MegapoolStakeWithoutProofEnabledPath, value, opts) +} +func EstimateProposeStakeWithoutProofEnabledGas(rp *rocketpool.RocketPool, value bool, opts *bind.TransactOpts) (gaslimit.Limits, error) { + return security.EstimateProposeSetBoolGas(rp, fmt.Sprintf("set %s", psettings.MegapoolStakeWithoutProofEnabledPath), megapoolNamespace, psettings.MegapoolStakeWithoutProofEnabledPath, value, opts) +} diff --git a/rocketpool-cli/cli/saturn2-check.go b/rocketpool-cli/cli/saturn2-check.go index 039e950e8..fdc4453c7 100644 --- a/rocketpool-cli/cli/saturn2-check.go +++ b/rocketpool-cli/cli/saturn2-check.go @@ -23,7 +23,12 @@ func IsSaturn2OnlySetting(contract, setting string) bool { } return false case protocol.MegapoolSettingsContractName: - return setting == protocol.MegapoolExitDeficitPath + switch setting { + case protocol.MegapoolExitDeficitPath, protocol.MegapoolPrestakeChallengePeriodPath, + protocol.MegapoolStakeWithoutProofEnabledPath: + return true + } + return false default: return false } diff --git a/rocketpool-cli/pdao/commands.go b/rocketpool-cli/pdao/commands.go index a99146f84..66890aefd 100644 --- a/rocketpool-cli/pdao/commands.go +++ b/rocketpool-cli/pdao/commands.go @@ -3310,6 +3310,72 @@ func RegisterCommands(app *cli.Command, name string, aliases []string) { }, }, + { + Name: "prestake-challenge-period", + Aliases: []string{"pcp"}, + Usage: fmt.Sprintf("Propose updating the %s setting (requires Saturn 2); %s", protocol.MegapoolPrestakeChallengePeriodPath, durationUsage), + UsageText: "rocketpool pdao propose setting megapool prestake-challenge-period value", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "yes", + Aliases: []string{"y"}, + Usage: "Automatically confirm all interactive questions", + }, + &cli.StringFlag{ + Name: "to-json", + Usage: "Write this setting to a JSON file instead of submitting a proposal (creates the file or appends to it)", + }, + }, + Action: func(ctx context.Context, c *cli.Command) error { + + // Validate args + if err := cliutils.ValidateArgCount(c, 1); err != nil { + return err + } + value, err := cliutils.ValidateDuration("value", c.Args().Get(0)) + if err != nil { + return err + } + + // Run + return proposeSettingMegapoolPrestakeChallengePeriod(value, c.Bool("yes"), c.String("to-json")) + + }, + }, + + { + Name: "is-stake-without-proof-enabled", + Aliases: []string{"swpe"}, + Usage: fmt.Sprintf("Propose updating the %s setting (requires Saturn 2); %s", protocol.MegapoolStakeWithoutProofEnabledPath, boolUsage), + UsageText: "rocketpool pdao propose setting megapool is-stake-without-proof-enabled value", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "yes", + Aliases: []string{"y"}, + Usage: "Automatically confirm all interactive questions", + }, + &cli.StringFlag{ + Name: "to-json", + Usage: "Write this setting to a JSON file instead of submitting a proposal (creates the file or appends to it)", + }, + }, + Action: func(ctx context.Context, c *cli.Command) error { + + // Validate args + if err := cliutils.ValidateArgCount(c, 1); err != nil { + return err + } + value, err := cliutils.ValidateBool("value", c.Args().Get(0)) + if err != nil { + return err + } + + // Run + return proposeSettingMegapoolStakeWithoutProofEnabled(value, c.Bool("yes"), c.String("to-json")) + + }, + }, + { Name: "penalty-threshold", Aliases: []string{"pt"}, diff --git a/rocketpool-cli/pdao/get-settings.go b/rocketpool-cli/pdao/get-settings.go index 80578c7ff..da01f42da 100644 --- a/rocketpool-cli/pdao/get-settings.go +++ b/rocketpool-cli/pdao/get-settings.go @@ -164,6 +164,8 @@ func getSettings() error { fmt.Printf("\tPenalty Threshold: %.2f%%\n", math.WeiToEth(response.Megapool.PenaltyThreshold)*100) if response.Saturn2Deployed { fmt.Printf("\tExit Deficit: %.6f ETH\n", math.WeiToEth(response.Megapool.ExitDeficit)) + fmt.Printf("\tPrestake Challenge Period: %s\n", response.Megapool.PrestakeChallengePeriod) + fmt.Printf("\tStake Without Proof Enabled: %t\n", response.Megapool.StakeWithoutProofEnabled) } return nil diff --git a/rocketpool-cli/pdao/propose-settings-json_test.go b/rocketpool-cli/pdao/propose-settings-json_test.go index d5633c560..ce4de624c 100644 --- a/rocketpool-cli/pdao/propose-settings-json_test.go +++ b/rocketpool-cli/pdao/propose-settings-json_test.go @@ -52,6 +52,72 @@ func TestExitDeficitCommandToBatchJSON(t *testing.T) { } } +func TestPrestakeChallengePeriodCommandToBatchJSON(t *testing.T) { + for _, tt := range []struct { + name, command, value, want string + }{ + {"hours", "prestake-challenge-period", "12h", "43200"}, + {"duration", "prestake-challenge-period", "12h30m", "45000"}, + {"alias", "pcp", "36h", "129600"}, + } { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "batch.json") + app := &cli.Command{Name: "rocketpool"} + RegisterCommands(app, "pdao", nil) + args := []string{"rocketpool", "pdao", "propose", "setting", "megapool", tt.command, "--yes", "--to-json", path, tt.value} + if err := app.Run(context.Background(), args); err != nil { + t.Fatal(err) + } + settings, err := readBatchSettingsFile(path) + if err != nil { + t.Fatal(err) + } + want := api.PDAOBatchSetting{ + Contract: protocol.MegapoolSettingsContractName, + Setting: protocol.MegapoolPrestakeChallengePeriodPath, + Type: protocol.ProposalSettingTypeNameUint256, + Value: tt.want, + } + if len(settings) != 1 || settings[0] != want { + t.Fatalf("got %+v, want %+v", settings, want) + } + }) + } +} + +func TestStakeWithoutProofEnabledCommandToBatchJSON(t *testing.T) { + for _, tt := range []struct { + name, command, value, want string + }{ + {"true", "is-stake-without-proof-enabled", "true", "true"}, + {"yes", "is-stake-without-proof-enabled", "yes", "true"}, + {"false", "swpe", "no", "false"}, + } { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "batch.json") + app := &cli.Command{Name: "rocketpool"} + RegisterCommands(app, "pdao", nil) + args := []string{"rocketpool", "pdao", "propose", "setting", "megapool", tt.command, "--yes", "--to-json", path, tt.value} + if err := app.Run(context.Background(), args); err != nil { + t.Fatal(err) + } + settings, err := readBatchSettingsFile(path) + if err != nil { + t.Fatal(err) + } + want := api.PDAOBatchSetting{ + Contract: protocol.MegapoolSettingsContractName, + Setting: protocol.MegapoolStakeWithoutProofEnabledPath, + Type: protocol.ProposalSettingTypeNameBool, + Value: tt.want, + } + if len(settings) != 1 || settings[0] != want { + t.Fatalf("got %+v, want %+v", settings, want) + } + }) + } +} + func TestWriteSettingToBatchJSON_CreateAndAppend(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "batch.json") @@ -110,7 +176,7 @@ func TestWriteSettingToBatchJSON_RejectsUnsupportedSettings(t *testing.T) { wantErr error }{ {"address list", protocol.NetworkSettingsContractName, protocol.NetworkAllowListedControllersPath, "0x1", protocol.ErrUnsupportedBatchSetting}, - {"removed prestake period", protocol.MegapoolSettingsContractName, "prestake.challenge.period", "36", protocol.ErrUnknownPDAOSetting}, + {"unprefixed prestake path", protocol.MegapoolSettingsContractName, "prestake.challenge.period", "36", protocol.ErrUnknownPDAOSetting}, } { t.Run(tt.name, func(t *testing.T) { path := filepath.Join(t.TempDir(), "batch.json") diff --git a/rocketpool-cli/pdao/propose-settings.go b/rocketpool-cli/pdao/propose-settings.go index 2b53a67d2..651280f3b 100644 --- a/rocketpool-cli/pdao/propose-settings.go +++ b/rocketpool-cli/pdao/propose-settings.go @@ -370,6 +370,16 @@ func proposeSettingMegapoolExitDeficit(value *big.Int, yes bool, toJson string) return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolExitDeficitPath, trueValue, yes, toJson) } +func proposeSettingMegapoolPrestakeChallengePeriod(value time.Duration, yes bool, toJson string) error { + trueValue := fmt.Sprint(uint64(value.Seconds())) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolPrestakeChallengePeriodPath, trueValue, yes, toJson) +} + +func proposeSettingMegapoolStakeWithoutProofEnabled(value bool, yes bool, toJson string) error { + trueValue := fmt.Sprint(value) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolStakeWithoutProofEnabledPath, trueValue, yes, toJson) +} + func proposeSettingPerformanceExitsEnabled(value bool, yes bool, toJson string) error { trueValue := fmt.Sprint(value) return proposeSetting(protocol.NetworkSettingsContractName, protocol.PerformanceExitsEnabledSettingPath, trueValue, yes, toJson) diff --git a/rocketpool-cli/security/commands.go b/rocketpool-cli/security/commands.go index b53ee1c31..ec3f83a54 100644 --- a/rocketpool-cli/security/commands.go +++ b/rocketpool-cli/security/commands.go @@ -300,6 +300,43 @@ func RegisterCommands(app *cli.Command, name string, aliases []string) { }, }, + { + Name: "megapool", + Aliases: []string{"g"}, + Usage: "Megapool settings", + Commands: []*cli.Command{ + + { + Name: "is-stake-without-proof-enabled", + Aliases: []string{"swpe"}, + Usage: fmt.Sprintf("Propose updating the %s setting (requires Saturn 2); %s", protocol.MegapoolStakeWithoutProofEnabledPath, boolUsage), + UsageText: "rocketpool security propose setting megapool is-stake-without-proof-enabled value", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "yes", + Aliases: []string{"y"}, + Usage: "Automatically confirm all interactive questions", + }, + }, + Action: func(ctx context.Context, c *cli.Command) error { + + // Validate args + if err := cliutils.ValidateArgCount(c, 1); err != nil { + return err + } + value, err := cliutils.ValidateBool("value", c.Args().Get(0)) + if err != nil { + return err + } + + // Run + return proposeSettingMegapoolStakeWithoutProofEnabled(value, c.Bool("yes")) + + }, + }, + }, + }, + { Name: "network", Aliases: []string{"ne"}, diff --git a/rocketpool-cli/security/propose-settings.go b/rocketpool-cli/security/propose-settings.go index 6dd29c918..1d9652e56 100644 --- a/rocketpool-cli/security/propose-settings.go +++ b/rocketpool-cli/security/propose-settings.go @@ -87,6 +87,11 @@ func proposeSettingPerformanceExitsEnabled(value bool, yes bool) error { return proposeSetting(protocol.NetworkSettingsContractName, protocol.PerformanceExitsEnabledSettingPath, trueValue, yes) } +func proposeSettingMegapoolStakeWithoutProofEnabled(value bool, yes bool) error { + trueValue := fmt.Sprint(value) + return proposeSetting(protocol.MegapoolSettingsContractName, protocol.MegapoolStakeWithoutProofEnabledPath, trueValue, yes) +} + // Master general proposal function func proposeSetting(contract string, setting string, value string, yes bool) error { // Get RP client diff --git a/rocketpool/api/pdao/get-settings.go b/rocketpool/api/pdao/get-settings.go index 2d7a615ed..9f29bb272 100644 --- a/rocketpool/api/pdao/get-settings.go +++ b/rocketpool/api/pdao/get-settings.go @@ -198,6 +198,18 @@ func getSettings(c *cli.Command) (*api.GetPDAOSettingsResponse, error) { response.Megapool.ExitDeficit, err = protocol.GetMegapoolExitDeficit(rp, nil) return err }) + + wg.Go(func() error { + var err error + response.Megapool.PrestakeChallengePeriod, err = protocol.GetPrestakeChallengePeriod(rp, nil) + return err + }) + + wg.Go(func() error { + var err error + response.Megapool.StakeWithoutProofEnabled, err = protocol.GetStakeWithoutProofEnabled(rp, nil) + return err + }) } // === Performance === diff --git a/rocketpool/api/pdao/propose-settings.go b/rocketpool/api/pdao/propose-settings.go index 88ad37f22..96a8bee5c 100644 --- a/rocketpool/api/pdao/propose-settings.go +++ b/rocketpool/api/pdao/propose-settings.go @@ -1101,6 +1101,26 @@ func canProposeSetting(c *cli.Command, contractName string, settingName string, if err != nil { return nil, fmt.Errorf("error estimating gas for proposing ExitDeficit: %w", err) } + // PrestakeChallengePeriod + case protocol.MegapoolPrestakeChallengePeriodPath: + newValue, err := cliutils.ValidateBigInt(valueName, value) + if err != nil { + return nil, err + } + response.GasLimits, err = protocol.EstimateProposePrestakeChallengePeriod(rp, newValue, blockNumber, pollard, opts) + if err != nil { + return nil, fmt.Errorf("error estimating gas for proposing PrestakeChallengePeriod: %w", err) + } + // StakeWithoutProofEnabled + case protocol.MegapoolStakeWithoutProofEnabledPath: + newValue, err := cliutils.ValidateBool(valueName, value) + if err != nil { + return nil, err + } + response.GasLimits, err = protocol.EstimateProposeStakeWithoutProofEnabledGas(rp, newValue, blockNumber, pollard, opts) + if err != nil { + return nil, fmt.Errorf("error estimating gas for proposing StakeWithoutProofEnabled: %w", err) + } } } @@ -2111,6 +2131,26 @@ func proposeSetting(c *cli.Command, contractName string, settingName string, val if err != nil { return nil, fmt.Errorf("error proposing ExitDeficit: %w", err) } + // PrestakeChallengePeriod + case protocol.MegapoolPrestakeChallengePeriodPath: + newValue, err := cliutils.ValidateBigInt(valueName, value) + if err != nil { + return nil, err + } + proposalID, hash, err = protocol.ProposePrestakeChallengePeriod(rp, newValue, blockNumber, pollard, opts) + if err != nil { + return nil, fmt.Errorf("error proposing PrestakeChallengePeriod: %w", err) + } + // StakeWithoutProofEnabled + case protocol.MegapoolStakeWithoutProofEnabledPath: + newValue, err := cliutils.ValidateBool(valueName, value) + if err != nil { + return nil, err + } + proposalID, hash, err = protocol.ProposeStakeWithoutProofEnabled(rp, newValue, blockNumber, pollard, opts) + if err != nil { + return nil, fmt.Errorf("error proposing StakeWithoutProofEnabled: %w", err) + } } } diff --git a/rocketpool/api/security/propose-settings.go b/rocketpool/api/security/propose-settings.go index 10e063c8b..ed5a5d30a 100644 --- a/rocketpool/api/security/propose-settings.go +++ b/rocketpool/api/security/propose-settings.go @@ -214,6 +214,20 @@ func canProposeSetting(c *cli.Command, contractName string, settingName string, } } + case protocol.MegapoolSettingsContractName: + switch settingName { + // StakeWithoutProofEnabled + case protocol.MegapoolStakeWithoutProofEnabledPath: + newValue, err := cliutils.ValidateBool(valueName, value) + if err != nil { + return nil, err + } + response.GasLimits, err = security.EstimateProposeStakeWithoutProofEnabledGas(rp, newValue, opts) + if err != nil { + return nil, fmt.Errorf("error estimating gas for proposing StakeWithoutProofEnabled: %w", err) + } + } + } // Make sure a setting was actually hit @@ -418,6 +432,20 @@ func proposeSetting(c *cli.Command, contractName string, settingName string, val } } + case protocol.MegapoolSettingsContractName: + switch settingName { + // StakeWithoutProofEnabled + case protocol.MegapoolStakeWithoutProofEnabledPath: + newValue, err := cliutils.ValidateBool(valueName, value) + if err != nil { + return nil, err + } + proposalID, hash, err = security.ProposeStakeWithoutProofEnabled(rp, newValue, opts) + if err != nil { + return nil, fmt.Errorf("error proposing StakeWithoutProofEnabled: %w", err) + } + } + } // Make sure a setting was actually hit diff --git a/rocketpool/node/node.go b/rocketpool/node/node.go index 24525f949..6f98b3350 100644 --- a/rocketpool/node/node.go +++ b/rocketpool/node/node.go @@ -42,27 +42,28 @@ const ( // Keep exit requests in the scan for seven days after the cooperative phase. exitRequestEnforcementWindow = 7 * 24 * time.Hour - DownloadRewardsTreesColor = color.FgGreen - MetricsColor = color.FgHiYellow - ManageFeeRecipientColor = color.FgHiCyan - DefendPdaoPropsColor = color.FgYellow - VerifyPdaoPropsColor = color.FgYellow - DistributeMinipoolsColor = color.FgHiGreen - ErrorColor = color.FgRed - WarningColor = color.FgYellow - ObserveWarningColor = color.FgHiRed - UpdateColor = color.FgHiWhite - PrestakeMegapoolValidatorColor = color.FgHiGreen - StakeMegapoolValidatorColor = color.FgHiBlue - NotifyValidatorExitColor = color.FgHiYellow - NotifyFinalBalanceColor = color.FgHiMagenta - CheckMinipoolExitRequestsColor = color.FgHiCyan - CheckMegapoolExitRequestsColor = color.FgCyan - DefendChallengeExitColor = color.FgHiGreen - DefendChallengePerformanceColor = color.FgHiBlue - ProvisionExpressTickets = color.FgMagenta - SetUseLatestDelegateColor = color.FgBlue - CheckPortConnectivityColor = color.FgHiYellow + DownloadRewardsTreesColor = color.FgGreen + MetricsColor = color.FgHiYellow + ManageFeeRecipientColor = color.FgHiCyan + DefendPdaoPropsColor = color.FgYellow + VerifyPdaoPropsColor = color.FgYellow + DistributeMinipoolsColor = color.FgHiGreen + ErrorColor = color.FgRed + WarningColor = color.FgYellow + ObserveWarningColor = color.FgHiRed + UpdateColor = color.FgHiWhite + PrestakeMegapoolValidatorColor = color.FgHiGreen + ValidatePrestakedValidatorsColor = color.FgWhite + StakeMegapoolValidatorColor = color.FgHiBlue + NotifyValidatorExitColor = color.FgHiYellow + NotifyFinalBalanceColor = color.FgHiMagenta + CheckMinipoolExitRequestsColor = color.FgHiCyan + CheckMegapoolExitRequestsColor = color.FgCyan + DefendChallengeExitColor = color.FgHiGreen + DefendChallengePerformanceColor = color.FgHiBlue + ProvisionExpressTickets = color.FgMagenta + SetUseLatestDelegateColor = color.FgBlue + CheckPortConnectivityColor = color.FgHiYellow ) // Register node command @@ -285,6 +286,10 @@ func run(c *cli.Command) error { if err != nil { return err } + validatePrestakedValidators, err := newValidatePrestakedValidators(c, log.NewColorLogger(ValidatePrestakedValidatorsColor)) + if err != nil { + return err + } var checkPorts *connectivity.CheckPortConnectivity checkPorts, err = connectivity.NewCheckPortConnectivity(c, cfg, log.NewColorLogger(CheckPortConnectivityColor)) if err != nil { @@ -440,6 +445,14 @@ func run(c *cli.Command) error { } } + // Run the prestaked validator signature check + if err := validatePrestakedValidators.run(state); err != nil { + errorLog.Println(err) + } + if !sleepWithContext(ctx, taskCooldown) { + return + } + // Run the megapool stake check if err := stakeMegapoolValidators.run(state); err != nil { errorLog.Println(err) diff --git a/rocketpool/node/stake-megapool-validator.go b/rocketpool/node/stake-megapool-validator.go index 6d07123e9..f862ed387 100644 --- a/rocketpool/node/stake-megapool-validator.go +++ b/rocketpool/node/stake-megapool-validator.go @@ -1,6 +1,8 @@ package node import ( + "context" + "fmt" "math/big" "strconv" @@ -10,6 +12,7 @@ import ( "github.com/rocket-pool/smartnode/bindings/megapool" "github.com/rocket-pool/smartnode/bindings/rocketpool" + "github.com/rocket-pool/smartnode/bindings/settings/protocol" "github.com/rocket-pool/smartnode/bindings/transactions" "github.com/rocket-pool/smartnode/bindings/types" @@ -24,6 +27,67 @@ import ( "github.com/rocket-pool/smartnode/shared/types/eth2" ) +type megapoolStakeAction int + +const ( + stakeSkip megapoolStakeAction = iota + stakeWithProof + stakeWithoutProof +) + +// megapoolStakeChoice is the pure input to the proof-versus-proofless decision. +type megapoolStakeChoice struct { + inPrestake bool + inBeaconState bool + prooflessEnabled bool + signatureRetained bool + deadline *big.Int + headTimestamp uint64 +} + +type prestakeStakeCandidate struct { + pubkey types.ValidatorPubkey + beaconIndex string +} + +// chooseMegapoolStake keeps proof staking whenever the validator is in the selected beacon state, +// including before the challenge deadline. stakeWithoutProof is only for a prestake the state does +// not contain yet, after the stored deadline, when the protocol still has the signature. +func chooseMegapoolStake(c megapoolStakeChoice) megapoolStakeAction { + if !c.inPrestake { + return stakeSkip + } + if c.inBeaconState { + return stakeWithProof + } + if !c.prooflessEnabled || !c.signatureRetained || !challengeDeadlineElapsed(c.deadline, c.headTimestamp) { + return stakeSkip + } + return stakeWithoutProof +} + +// stakeWithoutProof reverts until the execution block timestamp reaches the validator's stored deadline. +// A zero deadline means this prestake never received one. +func challengeDeadlineElapsed(deadline *big.Int, headTimestamp uint64) bool { + if deadline == nil || deadline.Sign() <= 0 { + return false + } + return deadline.Cmp(new(big.Int).SetUint64(headTimestamp)) <= 0 +} + +// validatorInSelectedBeaconState reports whether validatorIndex is inside the beacon state selected for proofs. +// An empty index means the beacon chain does not know the validator yet. +func validatorInSelectedBeaconState(validatorIndex string, stateValidatorCount int) (bool, error) { + if validatorIndex == "" { + return false, nil + } + index, err := strconv.ParseUint(validatorIndex, 10, 64) + if err != nil { + return false, fmt.Errorf("error parsing validator index %s: %w", validatorIndex, err) + } + return index < uint64(stateValidatorCount), nil +} + // Stake megapool validator task type stakeMegapoolValidator struct { c *cli.Command @@ -126,53 +190,98 @@ func (t *stakeMegapoolValidator) run(state *state.NetworkStateIndex) error { return err } - // store validators that need to be staked - validatorsToStake := make(map[uint32]types.ValidatorPubkey) - - for i := uint32(0); i < uint32(len(validatorInfo)); i++ { - if validatorInfo[i].InPrestake && validatorInfo[i].BeaconStatus.Index != "" { - validatorsToStake[validatorInfo[i].ValidatorId] = types.ValidatorPubkey(validatorInfo[i].PubKey) + // Every prestaked validator is a candidate. An empty beacon index still needs the proofless path. + validatorsToStake := make(map[uint32]prestakeStakeCandidate) + for i := range validatorInfo { + if !validatorInfo[i].InPrestake { + continue + } + validatorsToStake[validatorInfo[i].ValidatorId] = prestakeStakeCandidate{ + pubkey: types.ValidatorPubkey(validatorInfo[i].PubKey), + beaconIndex: validatorInfo[i].BeaconStatus.Index, } } - - // Check if we have any validators to stake if len(validatorsToStake) == 0 { return nil } - // Load the beacon state - beaconState, slotTimestamp, err := services.GetHeadBeaconState(t.bc, t.rp.Client) - if err != nil { - return err + // getStakeWithoutProofEnabled and stakeWithoutProof are Saturn 2 methods. + // A failure here must not send a transaction that the delegate would revert. + prooflessEnabled := false + if state.Saturn2Deployed { + prooflessEnabled, err = protocol.GetStakeWithoutProofEnabled(t.rp, opts) + if err != nil { + return err + } + } + if !prooflessEnabled && !candidatesHaveBeaconIndex(validatorsToStake) { + return nil + } + + // Proofs need the beacon state. A prestake the beacon has not seen only needs the execution + // head timestamp, which is the earliest block.timestamp the contract can observe next. + var beaconState eth2.BeaconState + var headTimestamp uint64 + if candidatesHaveBeaconIndex(validatorsToStake) { + beaconState, headTimestamp, err = services.GetHeadBeaconState(t.bc, t.rp.Client) + if err != nil { + return err + } + } else { + header, err := t.rp.Client.HeaderByNumber(context.Background(), nil) + if err != nil { + return fmt.Errorf("error getting execution head: %w", err) + } + if header == nil { + return fmt.Errorf("execution head is not available") + } + headTimestamp = header.Time + } + stateValidatorCount := 0 + if beaconState != nil { + stateValidatorCount = len(beaconState.GetValidators()) } - // Iterate over validators to stake. stakedValidators := 0 validatorsProcessed := 0 const batchSize = 6 - for validatorId, validatorPubkey := range validatorsToStake { + var stakeErr error + for validatorId, candidate := range validatorsToStake { if validatorsProcessed >= batchSize { break } - // Log - t.log.Printlnf("The validator id %d needs to be staked", validatorId) - // Check if the validator is included in the selected beacon state before attempting proof generation - validatorIndexStr, err := t.bc.GetValidatorIndex(validatorPubkey) + inState, beaconIndex, err := t.validatorInBeaconState(candidate, stateValidatorCount) if err != nil { - return err + stakeErr = err + break } - validatorIndex, err := strconv.ParseUint(validatorIndexStr, 10, 64) - if err != nil { - return err + + var action megapoolStakeAction + if inState { + action = stakeWithProof + } else { + action, err = t.prooflessStakeAction(mp, opts, validatorId, prooflessEnabled, headTimestamp) + if err != nil { + stakeErr = err + break + } } - if validatorIndex >= uint64(len(beaconState.GetValidators())) { - t.log.Printlnf("Validator id %d (beacon index %d) is not yet included in the selected beacon state. Will retry on next cycle.", validatorId, validatorIndex) + if action == stakeSkip { + // prooflessStakeAction already logged why this prestake is waiting. + // With proofless staking disabled, keep the previous retry for validators the beacon already lists. + if !prooflessEnabled && beaconIndex != "" { + t.log.Printlnf("Validator id %d (beacon index %s) is not yet included in the selected beacon state. Will retry on next cycle.", validatorId, beaconIndex) + } continue } - // Call Stake - err = t.stakeValidator(t.rp, beaconState, slotTimestamp, mp, validatorId, validatorPubkey) + t.log.Printlnf("The validator id %d needs to be staked", validatorId) + if action == stakeWithoutProof { + err = t.stakeValidatorWithoutProof(mp, validatorId) + } else { + err = t.stakeValidator(t.rp, beaconState, headTimestamp, mp, validatorId, candidate.pubkey) + } if err != nil { t.log.Printlnf("Error staking validator %d: %v", validatorId, err) break @@ -187,7 +296,7 @@ func (t *stakeMegapoolValidator) run(state *state.NetworkStateIndex) error { } } - return nil + return stakeErr } func (t *stakeMegapoolValidator) stakeValidator(rp *rocketpool.RocketPool, beaconState eth2.BeaconState, slotTimestamp uint64, mp megapool.Megapool, validatorId uint32, validatorPubkey types.ValidatorPubkey) error { @@ -251,3 +360,99 @@ func (t *stakeMegapoolValidator) stakeValidator(rp *rocketpool.RocketPool, beaco // Return return nil } + +func (t *stakeMegapoolValidator) validatorInBeaconState(candidate prestakeStakeCandidate, stateValidatorCount int) (bool, string, error) { + index := candidate.beaconIndex + if index != "" { + // Refresh the index. The status used to build the candidate can be one slot ahead of the proof state. + refreshed, err := t.bc.GetValidatorIndex(candidate.pubkey) + if err != nil { + return false, index, err + } + index = refreshed + } + included, err := validatorInSelectedBeaconState(index, stateValidatorCount) + return included, index, err +} + +func (t *stakeMegapoolValidator) prooflessStakeAction(mp megapool.Megapool, opts *bind.CallOpts, validatorId uint32, prooflessEnabled bool, headTimestamp uint64) (megapoolStakeAction, error) { + if !prooflessEnabled { + return stakeSkip, nil + } + deadline, err := mp.GetValidatorChallengeDeadline(validatorId, opts) + if err != nil { + return stakeSkip, fmt.Errorf("error getting validator %d challenge deadline: %w", validatorId, err) + } + signature, err := mp.GetValidatorPrestakeSignature(validatorId, opts) + if err != nil { + return stakeSkip, fmt.Errorf("error getting validator %d prestake signature: %w", validatorId, err) + } + action := chooseMegapoolStake(megapoolStakeChoice{ + inPrestake: true, + inBeaconState: false, + prooflessEnabled: true, + signatureRetained: len(signature) != 0, + deadline: deadline, + headTimestamp: headTimestamp, + }) + if action == stakeSkip { + t.logProoflessSkip(validatorId, deadline, len(signature) != 0, headTimestamp) + } + return action, nil +} + +func (t *stakeMegapoolValidator) logProoflessSkip(validatorId uint32, deadline *big.Int, signatureRetained bool, headTimestamp uint64) { + if signatureRetained && deadline != nil && deadline.Sign() > 0 && !challengeDeadlineElapsed(deadline, headTimestamp) { + t.log.Printlnf("Validator id %d is not yet included in the selected beacon state and the challenge period has not elapsed. Will retry on next cycle.", validatorId) + return + } + t.log.Printlnf("Validator id %d is not yet included in the selected beacon state and is not eligible for proofless staking. Will retry on next cycle.", validatorId) +} + +func (t *stakeMegapoolValidator) stakeValidatorWithoutProof(mp megapool.Megapool, validatorId uint32) error { + opts, err := t.w.GetNodeAccountTransactor() + if err != nil { + return err + } + + t.log.Printlnf("Staking validator %d without a beacon state proof. The challenge period has elapsed and the validator is not in the selected beacon state.", validatorId) + + gasLimits, err := mp.EstimateStakeWithoutProofGas(validatorId, opts) + if err != nil { + t.log.Printlnf("Could not estimate the gas required to stake megapool validator %d without a proof: %v", validatorId, err) + return err + } + maxFee := t.maxFee + if maxFee == nil || maxFee.Uint64() == 0 { + maxFee, err = rpgas.GetHeadlessMaxFeeWeiWithLatestBlock(t.cfg, t.rp) + if err != nil { + return err + } + } + if !gasLimits.PrintAndCheck(true, t.gasThreshold, &t.log, maxFee, t.gasLimit) { + return nil + } + + opts.GasFeeCap = maxFee + opts.GasTipCap = GetPriorityFee(t.maxPriorityFee, maxFee) + opts.GasLimit = gasLimits.Safe + + txHash, err := mp.StakeWithoutProof(validatorId, opts) + if err != nil { + return err + } + if err := transactions.PrintAndWaitForTransaction(t.cfg, txHash, t.rp.Client, &t.log); err != nil { + return err + } + t.log.Printlnf("Successfully staked validator %d.", validatorId) + return nil +} + +func candidatesHaveBeaconIndex(candidates map[uint32]prestakeStakeCandidate) bool { + for _, candidate := range candidates { + if candidate.beaconIndex != "" { + return true + } + } + return false +} diff --git a/rocketpool/node/stake-megapool-validator_test.go b/rocketpool/node/stake-megapool-validator_test.go new file mode 100644 index 000000000..811457f0c --- /dev/null +++ b/rocketpool/node/stake-megapool-validator_test.go @@ -0,0 +1,98 @@ +package node + +import ( + "math/big" + "testing" +) + +func TestChooseMegapoolStake(t *testing.T) { + deadline := big.NewInt(1_000) + eligible := megapoolStakeChoice{ + inPrestake: true, + prooflessEnabled: true, + signatureRetained: true, + deadline: deadline, + headTimestamp: 1_000, + } + + if got := chooseMegapoolStake(eligible); got != stakeWithoutProof { + t.Fatalf("deadline equal to head timestamp chose %d", got) + } + eligible.headTimestamp = 1_001 + if got := chooseMegapoolStake(eligible); got != stakeWithoutProof { + t.Fatalf("deadline before head timestamp chose %d", got) + } + + waiting := eligible + waiting.headTimestamp = 999 + if got := chooseMegapoolStake(waiting); got != stakeSkip { + t.Fatalf("deadline one second in the future chose %d", got) + } + + inState := waiting + inState.inBeaconState = true + if got := chooseMegapoolStake(inState); got != stakeWithProof { + t.Fatalf("validator in the beacon state before the deadline chose %d", got) + } + inState.prooflessEnabled = false + inState.signatureRetained = false + inState.deadline = nil + if got := chooseMegapoolStake(inState); got != stakeWithProof { + t.Fatalf("validator in the beacon state with proofless staking disabled chose %d", got) + } + + notPrestake := eligible + notPrestake.inPrestake = false + notPrestake.inBeaconState = true + if got := chooseMegapoolStake(notPrestake); got != stakeSkip { + t.Fatalf("validator that is not prestaked chose %d", got) + } + + disabled := eligible + disabled.prooflessEnabled = false + if got := chooseMegapoolStake(disabled); got != stakeSkip { + t.Fatalf("proofless staking disabled chose %d", got) + } + missingSignature := eligible + missingSignature.signatureRetained = false + if got := chooseMegapoolStake(missingSignature); got != stakeSkip { + t.Fatalf("missing retained signature chose %d", got) + } + unsetDeadline := eligible + unsetDeadline.deadline = big.NewInt(0) + if got := chooseMegapoolStake(unsetDeadline); got != stakeSkip { + t.Fatalf("zero deadline chose %d", got) + } + if got := chooseMegapoolStake(megapoolStakeChoice{ + inPrestake: true, + prooflessEnabled: true, + signatureRetained: true, + deadline: nil, + headTimestamp: 1_000, + }); got != stakeSkip { + t.Fatalf("nil deadline chose %d", got) + } + + huge := new(big.Int).Lsh(big.NewInt(1), 64) + if challengeDeadlineElapsed(huge, ^uint64(0)) { + t.Fatal("deadline above uint64 was treated as elapsed") + } +} + +func TestValidatorInSelectedBeaconState(t *testing.T) { + included, err := validatorInSelectedBeaconState("", 10) + if err != nil || included { + t.Fatalf("empty index = %v, %v", included, err) + } + included, err = validatorInSelectedBeaconState("2", 3) + if err != nil || !included { + t.Fatalf("index inside the state = %v, %v", included, err) + } + included, err = validatorInSelectedBeaconState("2", 2) + if err != nil || included { + t.Fatalf("index at the end of the state = %v, %v", included, err) + } + if _, err := validatorInSelectedBeaconState("nope", 2); err == nil { + t.Fatal("non-numeric index did not fail") + } +} diff --git a/rocketpool/node/validate-prestaked-validators.go b/rocketpool/node/validate-prestaked-validators.go new file mode 100644 index 000000000..88e52406c --- /dev/null +++ b/rocketpool/node/validate-prestaked-validators.go @@ -0,0 +1,419 @@ +package node + +import ( + "bytes" + "errors" + "fmt" + "math/big" + + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/prysmaticlabs/prysm/v5/beacon-chain/core/signing" + prdeposit "github.com/prysmaticlabs/prysm/v5/contracts/deposit" + ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1" + "github.com/urfave/cli/v3" + eth2types "github.com/wealdtech/go-eth2-types/v2" + + "github.com/rocket-pool/smartnode/bindings/megapool" + "github.com/rocket-pool/smartnode/bindings/rocketpool" + "github.com/rocket-pool/smartnode/bindings/transactions" + + log "github.com/rocket-pool/smartnode/shared/logger" + "github.com/rocket-pool/smartnode/shared/services" + "github.com/rocket-pool/smartnode/shared/services/beacon" + "github.com/rocket-pool/smartnode/shared/services/config" + rpgas "github.com/rocket-pool/smartnode/shared/services/gas" + "github.com/rocket-pool/smartnode/shared/services/state" + "github.com/rocket-pool/smartnode/shared/services/wallet" + "github.com/rocket-pool/smartnode/shared/types/eth2/generic" +) + +const ( + // prestakeAmountGwei is the 1 ETH deposit checked by challengeInvalidSignature. + prestakeAmountGwei uint64 = 1_000_000_000 + // prestakeIndexPageSize is how many global indices one getPrestakedValidatorIndices call inspects. + prestakeIndexPageSize int64 = 200 + // maxPrestakeChallengesPerCycle keeps one pass from holding the node loop on a large backlog. + maxPrestakeChallengesPerCycle = 8 + maxPendingDepositDissolvesPerCycle = 8 +) + +type prestakeValidation int + +const ( + prestakeSkipped prestakeValidation = iota + prestakeValid + prestakeInvalidSignature +) + +// Validate prestaked validators task +type validatePrestakedValidators struct { + c *cli.Command + log log.ColorLogger + cfg *config.RocketPoolConfig + w wallet.Wallet + rp *rocketpool.RocketPool + bc beacon.Client + gasThreshold float64 + maxFee *big.Int + maxPriorityFee *big.Int + gasLimit uint64 +} + +// Create validate prestaked validators task +func newValidatePrestakedValidators(c *cli.Command, logger log.ColorLogger) (*validatePrestakedValidators, error) { + cfg, err := services.GetConfig(c) + if err != nil { + return nil, err + } + w, err := services.GetWallet(c) + if err != nil { + return nil, err + } + rp, err := services.GetRocketPool(c) + if err != nil { + return nil, err + } + bc, err := services.GetBeaconClient(c) + if err != nil { + return nil, err + } + + gas := loadAutoTxGas(cfg, &logger) + return &validatePrestakedValidators{ + c: c, + log: logger, + cfg: cfg, + w: w, + rp: rp, + bc: bc, + gasThreshold: gas.thresholdGwei, + maxFee: gas.maxFee, + maxPriorityFee: gas.maxPriorityFee, + gasLimit: 0, + }, nil +} + +// Check prestaked validators, challenge invalid deposit signatures, and dissolve +// validators whose pending beacon deposit is signed to the wrong withdrawal credentials. +func (t *validatePrestakedValidators) run(state *state.NetworkStateIndex) error { + if !state.Saturn2Deployed { + return nil + } + + t.log.Println("Checking prestaked megapool validators...") + + nodeAccount, err := t.w.GetNodeAccount() + if err != nil { + return err + } + opts := &bind.CallOpts{ + BlockNumber: new(big.Int).SetUint64(state.ElBlockNumber), + } + // challengeInvalidSignature and dissolvePendingDeposit require the caller to have a deployed megapool. + canChallenge, err := megapool.GetMegapoolDeployed(t.rp, nodeAccount.Address, opts) + if err != nil { + return err + } + + depositDomain, err := signing.ComputeDomain(eth2types.DomainDeposit, state.BeaconConfig.GenesisForkVersion, eth2types.ZeroGenesisValidatorsRoot) + if err != nil { + return fmt.Errorf("error computing deposit domain: %w", err) + } + + indices, failed, err := t.prestakedIndices(opts) + if err != nil { + return err + } + indices = append(indices, failed...) + + var prestaked []megapool.ValidatorPrestakeInfo + var invalid []megapool.ValidatorPrestakeInfo + for _, index := range indices { + info, err := megapool.GetValidatorPrestakeInfo(t.rp, new(big.Int).SetUint64(index), opts) + if err != nil { + t.log.Printlnf("Error reading prestake info for global index %d: %v", index, err) + continue + } + if !info.ValidatorInfo.InPrestake { + continue + } + prestaked = append(prestaked, info) + credentials := services.CalculateMegapoolWithdrawalCredentials(info.MegapoolAddress) + valid := prestakeSignatureValid(info.Pubkey, info.Signature, credentials, depositDomain) + if classifyPrestake(info, valid) == prestakeInvalidSignature { + t.log.Printlnf("Invalid prestake signature for megapool %s validator %d (global index %d)", info.MegapoolAddress.Hex(), info.ValidatorId, index) + invalid = append(invalid, info) + } + } + if !canChallenge { + if len(invalid) > 0 { + t.log.Printlnf("%d prestaked validators have invalid signatures. This node cannot challenge until its megapool is deployed.", len(invalid)) + } + return nil + } + if err := t.challengeInvalid(invalid); err != nil { + return err + } + return t.dissolveWrongCredentialDeposits(prestaked, depositDomain) +} + +func (t *validatePrestakedValidators) prestakedIndices(opts *bind.CallOpts) (indices []uint64, failed []uint64, err error) { + offset := big.NewInt(0) + limit := big.NewInt(prestakeIndexPageSize) + for { + page, err := megapool.GetPrestakedValidatorIndices(t.rp, offset, limit, opts) + if err != nil { + return nil, nil, err + } + for _, index := range page.Indices { + value, err := uint256ToUint64(index) + if err != nil { + return nil, nil, fmt.Errorf("prestaked index: %w", err) + } + indices = append(indices, value) + } + for _, index := range page.FailedIndices { + value, err := uint256ToUint64(index) + if err != nil { + return nil, nil, fmt.Errorf("failed prestaked index: %w", err) + } + failed = append(failed, value) + } + if !prestakePageAdvances(offset, page.NextIndex) { + return indices, failed, nil + } + offset = page.NextIndex + } +} + +func (t *validatePrestakedValidators) challengeInvalid(invalid []megapool.ValidatorPrestakeInfo) error { + submitted := 0 + for _, info := range invalid { + if submitted >= maxPrestakeChallengesPerCycle { + t.log.Printlnf("%d invalid prestake signatures remain for the next cycle", len(invalid)-submitted) + return nil + } + sent, err := t.challenge(info) + if err != nil { + t.log.Printlnf("Error challenging megapool %s validator %d: %v", info.MegapoolAddress.Hex(), info.ValidatorId, err) + continue + } + if !sent { + return nil + } + submitted++ + } + return nil +} + +func (t *validatePrestakedValidators) challenge(info megapool.ValidatorPrestakeInfo) (bool, error) { + opts, err := t.w.GetNodeAccountTransactor() + if err != nil { + return false, err + } + gasLimits, err := megapool.EstimateChallengeInvalidSignatureGas(t.rp, info.MegapoolAddress, info.ValidatorId, opts) + if err != nil { + return false, err + } + maxFee := t.maxFee + if maxFee == nil || maxFee.Sign() == 0 { + maxFee, err = rpgas.GetHeadlessMaxFeeWeiWithLatestBlock(t.cfg, t.rp) + if err != nil { + return false, err + } + } + if !gasLimits.PrintAndCheck(true, t.gasThreshold, &t.log, maxFee, t.gasLimit) { + return false, nil + } + opts.GasFeeCap = maxFee + opts.GasTipCap = GetPriorityFee(t.maxPriorityFee, maxFee) + opts.GasLimit = gasLimits.Safe + + tx, err := megapool.ChallengeInvalidSignature(t.rp, info.MegapoolAddress, info.ValidatorId, opts) + if err != nil { + return false, err + } + if err := transactions.PrintAndWaitForTransaction(t.cfg, tx.Hash(), t.rp.Client, &t.log); err != nil { + return false, err + } + t.log.Printlnf("Challenged invalid prestake signature for megapool %s validator %d", info.MegapoolAddress.Hex(), info.ValidatorId) + return true, nil +} + +type pendingDepositDissolve struct { + info megapool.ValidatorPrestakeInfo + depositIndex uint64 +} + +func (t *validatePrestakedValidators) dissolveWrongCredentialDeposits(prestaked []megapool.ValidatorPrestakeInfo, depositDomain []byte) error { + if len(prestaked) == 0 { + return nil + } + beaconState, slotTimestamp, err := services.GetHeadBeaconState(t.bc, t.rp.Client) + if err != nil { + return err + } + matches := wrongCredentialPendingDeposits(beaconState.GetPendingDeposits(), prestaked, depositDomain) + if len(matches) == 0 { + return nil + } + limit := maxPendingDepositDissolvesPerCycle + if len(matches) < limit { + limit = len(matches) + } else { + t.log.Printlnf("%d pending deposits with invalid withdrawal credentials remain for the next cycle", len(matches)-limit) + } + batch := matches[:limit] + indices := make([]uint64, len(batch)) + for i, match := range batch { + indices[i] = match.depositIndex + t.log.Printlnf("Pending deposit %d for megapool %s validator %d uses invalid withdrawal credentials", match.depositIndex, match.info.MegapoolAddress.Hex(), match.info.ValidatorId) + } + proofs, slotProof, err := services.PendingDepositProofsFromState(beaconState, indices) + if err != nil { + if errors.Is(err, generic.ErrPendingDepositProofUnsupported) { + t.log.Printlnf("%d prestaked validators have a valid pending deposit to the wrong withdrawal credentials. Dissolving them requires a Gloas beacon state.", len(matches)) + return nil + } + return err + } + for i, match := range batch { + sent, err := t.dissolvePendingDeposit(match.info, proofs[i], slotProof, slotTimestamp) + if err != nil { + t.log.Printlnf("Error dissolving megapool %s validator %d: %v", match.info.MegapoolAddress.Hex(), match.info.ValidatorId, err) + continue + } + if !sent { + return nil + } + } + return nil +} + +func (t *validatePrestakedValidators) dissolvePendingDeposit(info megapool.ValidatorPrestakeInfo, depositProof megapool.PendingDepositProof, slotProof megapool.SlotProof, slotTimestamp uint64) (bool, error) { + proofData, err := megapool.EncodePendingDepositProofBundleV1(depositProof, slotProof) + if err != nil { + return false, err + } + opts, err := t.w.GetNodeAccountTransactor() + if err != nil { + return false, err + } + gasLimits, err := megapool.EstimateDissolvePendingDepositGas(t.rp, info.MegapoolAddress, info.ValidatorId, slotTimestamp, megapool.PendingDepositProofVersion1, proofData, opts) + if err != nil { + return false, err + } + maxFee := t.maxFee + if maxFee == nil || maxFee.Sign() == 0 { + maxFee, err = rpgas.GetHeadlessMaxFeeWeiWithLatestBlock(t.cfg, t.rp) + if err != nil { + return false, err + } + } + if !gasLimits.PrintAndCheck(true, t.gasThreshold, &t.log, maxFee, t.gasLimit) { + return false, nil + } + opts.GasFeeCap = maxFee + opts.GasTipCap = GetPriorityFee(t.maxPriorityFee, maxFee) + opts.GasLimit = gasLimits.Safe + + tx, err := megapool.DissolvePendingDeposit(t.rp, info.MegapoolAddress, info.ValidatorId, slotTimestamp, megapool.PendingDepositProofVersion1, proofData, opts) + if err != nil { + return false, err + } + if err := transactions.PrintAndWaitForTransaction(t.cfg, tx.Hash(), t.rp.Client, &t.log); err != nil { + return false, err + } + t.log.Printlnf("Dissolved megapool %s validator %d for a pending deposit with invalid withdrawal credentials", info.MegapoolAddress.Hex(), info.ValidatorId) + return true, nil +} + +// wrongCredentialPendingDeposits returns prestaked validators whose pubkey appears +// in a pending deposit that is validly signed to withdrawal credentials other than +// that validator's megapool. One deposit dissolves a validator, so later deposits +// for the same validator are skipped. +func wrongCredentialPendingDeposits(deposits []*generic.PendingDeposit, prestaked []megapool.ValidatorPrestakeInfo, depositDomain []byte) []pendingDepositDissolve { + byPubkey := make(map[string][]megapool.ValidatorPrestakeInfo, len(prestaked)) + for _, info := range prestaked { + if !info.ValidatorInfo.InPrestake || len(info.Pubkey) == 0 { + continue + } + byPubkey[string(info.Pubkey)] = append(byPubkey[string(info.Pubkey)], info) + } + seen := make(map[string]struct{}) + var matches []pendingDepositDissolve + for index, deposit := range deposits { + if deposit == nil || len(deposit.Pubkey) == 0 || !pendingDepositSignatureValid(deposit, depositDomain) { + continue + } + for _, info := range byPubkey[string(deposit.Pubkey)] { + key := fmt.Sprintf("%s:%d", info.MegapoolAddress.Hex(), info.ValidatorId) + if _, ok := seen[key]; ok { + continue + } + credentials := services.CalculateMegapoolWithdrawalCredentials(info.MegapoolAddress) + if bytes.Equal(deposit.WithdrawalCredentials, credentials.Bytes()) { + continue + } + seen[key] = struct{}{} + matches = append(matches, pendingDepositDissolve{ + info: info, + depositIndex: uint64(index), + }) + } + } + return matches +} + +// pendingDepositSignatureValid reports whether the deposit signature verifies +// against that deposit's own withdrawal credentials and amount. +func pendingDepositSignatureValid(deposit *generic.PendingDeposit, depositDomain []byte) bool { + if deposit == nil || len(deposit.Pubkey) == 0 || len(deposit.Signature) == 0 || len(deposit.WithdrawalCredentials) == 0 { + return false + } + depositData := ðpb.Deposit_Data{ + Amount: deposit.Amount, + PublicKey: deposit.Pubkey, + WithdrawalCredentials: deposit.WithdrawalCredentials, + Signature: deposit.Signature, + } + return prdeposit.VerifyDepositSignature(depositData, depositDomain) == nil +} + +// classifyPrestake reports whether a prestake can be challenged. +// An empty signature is a legacy validator and cannot be challenged. +func classifyPrestake(info megapool.ValidatorPrestakeInfo, signatureValid bool) prestakeValidation { + if !info.ValidatorInfo.InPrestake || len(info.Signature) == 0 { + return prestakeSkipped + } + if signatureValid { + return prestakeValid + } + return prestakeInvalidSignature +} + +// prestakeSignatureValid reports whether the retained signature is a valid 1 ETH deposit into the megapool. +func prestakeSignatureValid(pubkey, signature []byte, withdrawalCredentials common.Hash, depositDomain []byte) bool { + if len(pubkey) == 0 || len(signature) == 0 { + return false + } + depositData := ðpb.Deposit_Data{ + Amount: prestakeAmountGwei, + PublicKey: pubkey, + WithdrawalCredentials: withdrawalCredentials.Bytes(), + Signature: signature, + } + return prdeposit.VerifyDepositSignature(depositData, depositDomain) == nil +} + +func prestakePageAdvances(offset, next *big.Int) bool { + return next != nil && next.Cmp(offset) > 0 +} + +func uint256ToUint64(value *big.Int) (uint64, error) { + if value == nil || value.Sign() < 0 || !value.IsUint64() { + return 0, fmt.Errorf("value %v does not fit in uint64", value) + } + return value.Uint64(), nil +} diff --git a/rocketpool/node/validate-prestaked-validators_test.go b/rocketpool/node/validate-prestaked-validators_test.go new file mode 100644 index 000000000..81d329c09 --- /dev/null +++ b/rocketpool/node/validate-prestaked-validators_test.go @@ -0,0 +1,183 @@ +package node + +import ( + "bytes" + "math/big" + "testing" + + "github.com/ethereum/go-ethereum/common" + "github.com/prysmaticlabs/prysm/v5/beacon-chain/core/signing" + "github.com/prysmaticlabs/prysm/v5/crypto/bls" + ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1" + eth2types "github.com/wealdtech/go-eth2-types/v2" + + "github.com/rocket-pool/smartnode/bindings/megapool" + "github.com/rocket-pool/smartnode/shared/services" + "github.com/rocket-pool/smartnode/shared/types/eth2/generic" +) + +func TestClassifyPrestake(t *testing.T) { + info := megapool.ValidatorPrestakeInfo{ + ValidatorInfo: megapool.ValidatorInfo{InPrestake: true}, + Signature: []byte{1}, + } + if got := classifyPrestake(info, true); got != prestakeValid { + t.Fatalf("valid signature classified as %d", got) + } + if got := classifyPrestake(info, false); got != prestakeInvalidSignature { + t.Fatalf("invalid signature classified as %d", got) + } + info.Signature = nil + if got := classifyPrestake(info, false); got != prestakeSkipped { + t.Fatalf("missing signature classified as %d", got) + } + info.Signature = []byte{1} + info.ValidatorInfo.InPrestake = false + if got := classifyPrestake(info, false); got != prestakeSkipped { + t.Fatalf("validator not in prestake classified as %d", got) + } +} + +func TestPrestakePageAdvances(t *testing.T) { + if prestakePageAdvances(big.NewInt(0), big.NewInt(0)) { + t.Fatal("cursor did not move") + } + if !prestakePageAdvances(big.NewInt(0), big.NewInt(prestakeIndexPageSize)) { + t.Fatal("cursor advanced") + } + if prestakePageAdvances(big.NewInt(10), nil) { + t.Fatal("nil cursor advanced") + } +} + +func TestPrestakeSignatureValid(t *testing.T) { + secret, err := bls.RandKey() + if err != nil { + t.Fatal(err) + } + pubkey := secret.PublicKey().Marshal() + megapoolAddress := common.HexToAddress("0x1111111111111111111111111111111111111111") + credentials := services.CalculateMegapoolWithdrawalCredentials(megapoolAddress) + domain, err := signing.ComputeDomain(eth2types.DomainDeposit, []byte{0, 0, 0, 0}, eth2types.ZeroGenesisValidatorsRoot) + if err != nil { + t.Fatal(err) + } + + signature, err := signDeposit(secret, pubkey, credentials, prestakeAmountGwei, domain) + if err != nil { + t.Fatal(err) + } + if !prestakeSignatureValid(pubkey, signature, credentials, domain) { + t.Fatal("expected the 1 ETH megapool deposit signature to verify") + } + + otherCredentials := services.CalculateMegapoolWithdrawalCredentials(common.HexToAddress("0x2222222222222222222222222222222222222222")) + if prestakeSignatureValid(pubkey, signature, otherCredentials, domain) { + t.Fatal("expected a signature over different withdrawal credentials to be invalid") + } + + wrongAmount, err := signDeposit(secret, pubkey, credentials, 32_000_000_000, domain) + if err != nil { + t.Fatal(err) + } + if prestakeSignatureValid(pubkey, wrongAmount, credentials, domain) { + t.Fatal("expected a signature over 32 ETH to be invalid") + } + if prestakeSignatureValid(pubkey, nil, credentials, domain) { + t.Fatal("expected an empty signature to be invalid") + } +} + +func TestWrongCredentialPendingDeposits(t *testing.T) { + secret, err := bls.RandKey() + if err != nil { + t.Fatal(err) + } + pubkey := secret.PublicKey().Marshal() + megapoolAddress := common.HexToAddress("0x1111111111111111111111111111111111111111") + megapoolCredentials := services.CalculateMegapoolWithdrawalCredentials(megapoolAddress) + wrongCredentials := services.CalculateMegapoolWithdrawalCredentials(common.HexToAddress("0x2222222222222222222222222222222222222222")) + domain, err := signing.ComputeDomain(eth2types.DomainDeposit, []byte{0, 0, 0, 0}, eth2types.ZeroGenesisValidatorsRoot) + if err != nil { + t.Fatal(err) + } + const amount = uint64(2_000_000_000) + signature, err := signDeposit(secret, pubkey, wrongCredentials, amount, domain) + if err != nil { + t.Fatal(err) + } + deposit := &generic.PendingDeposit{ + Pubkey: pubkey, + WithdrawalCredentials: append([]byte(nil), wrongCredentials.Bytes()...), + Amount: amount, + Signature: signature, + Slot: 3, + } + info := megapool.ValidatorPrestakeInfo{ + Pubkey: pubkey, + MegapoolAddress: megapoolAddress, + ValidatorId: 4, + ValidatorInfo: megapool.ValidatorInfo{InPrestake: true}, + } + + matches := wrongCredentialPendingDeposits([]*generic.PendingDeposit{deposit}, []megapool.ValidatorPrestakeInfo{info}, domain) + if len(matches) != 1 || matches[0].depositIndex != 0 || matches[0].info.ValidatorId != 4 { + t.Fatalf("expected the wrong-credential deposit to dissolve validator 4, got %+v", matches) + } + + goodSignature, err := signDeposit(secret, pubkey, megapoolCredentials, amount, domain) + if err != nil { + t.Fatal(err) + } + correct := *deposit + correct.WithdrawalCredentials = append([]byte(nil), megapoolCredentials.Bytes()...) + correct.Signature = goodSignature + if got := wrongCredentialPendingDeposits([]*generic.PendingDeposit{&correct}, []megapool.ValidatorPrestakeInfo{info}, domain); len(got) != 0 { + t.Fatalf("megapool credentials were treated as invalid: %+v", got) + } + + wrongAmount := *deposit + wrongAmount.Amount = amount + 1 + if got := wrongCredentialPendingDeposits([]*generic.PendingDeposit{&wrongAmount}, []megapool.ValidatorPrestakeInfo{info}, domain); len(got) != 0 { + t.Fatalf("an invalid signature was selected: %+v", got) + } + + otherPubkey := *deposit + otherPubkey.Pubkey = bytes.Repeat([]byte{9}, 48) + if got := wrongCredentialPendingDeposits([]*generic.PendingDeposit{&otherPubkey}, []megapool.ValidatorPrestakeInfo{info}, domain); len(got) != 0 { + t.Fatalf("a different pubkey was selected: %+v", got) + } + + notPrestake := info + notPrestake.ValidatorInfo.InPrestake = false + if got := wrongCredentialPendingDeposits([]*generic.PendingDeposit{deposit}, []megapool.ValidatorPrestakeInfo{notPrestake}, domain); len(got) != 0 { + t.Fatalf("a validator that is not prestaked was selected: %+v", got) + } + + second := *deposit + matches = wrongCredentialPendingDeposits([]*generic.PendingDeposit{deposit, &second}, []megapool.ValidatorPrestakeInfo{info}, domain) + if len(matches) != 1 || matches[0].depositIndex != 0 { + t.Fatalf("expected one dissolve for the first matching deposit, got %+v", matches) + } +} + +func signDeposit(secret bls.SecretKey, pubkey []byte, credentials common.Hash, amount uint64, domain []byte) ([]byte, error) { + message := ðpb.DepositMessage{ + PublicKey: pubkey, + WithdrawalCredentials: credentials.Bytes(), + Amount: amount, + } + root, err := message.HashTreeRoot() + if err != nil { + return nil, err + } + signingData := ðpb.SigningData{ + ObjectRoot: root[:], + Domain: domain, + } + signingRoot, err := signingData.HashTreeRoot() + if err != nil { + return nil, err + } + return secret.Sign(signingRoot[:]).Marshal(), nil +} diff --git a/shared/services/megapools.go b/shared/services/megapools.go index 457972c98..95321c4c1 100644 --- a/shared/services/megapools.go +++ b/shared/services/megapools.go @@ -146,6 +146,51 @@ func GetValidatorProofFromState(bc beacon.Client, validatorPubkey types.Validato return proof, slotProof, nil } +// PendingDepositProofsFromState builds version-1 pending deposit proofs for the +// given indices. StateSlot matches the anchor slot +func PendingDepositProofsFromState(beaconState eth2.BeaconState, indices []uint64) ([]megapool.PendingDepositProof, megapool.SlotProof, error) { + if beaconState == nil { + return nil, megapool.SlotProof{}, fmt.Errorf("beacon state is required") + } + deposits := beaconState.GetPendingDeposits() + proofBytes, slotProofBytes, err := beaconState.PendingDepositProofs(indices) + if err != nil { + return nil, megapool.SlotProof{}, err + } + if len(proofBytes) != len(indices) { + return nil, megapool.SlotProof{}, fmt.Errorf("pending deposit proof count %d does not match %d indices", len(proofBytes), len(indices)) + } + slot := beaconState.GetSlot() + proofs := make([]megapool.PendingDepositProof, len(indices)) + for i, index := range indices { + if index >= uint64(len(deposits)) || deposits[index] == nil { + return nil, megapool.SlotProof{}, fmt.Errorf("pending deposit %d is not in the beacon state", index) + } + deposit := deposits[index] + if len(deposit.WithdrawalCredentials) != 32 { + return nil, megapool.SlotProof{}, fmt.Errorf("pending deposit %d has withdrawal credentials of length %d", index, len(deposit.WithdrawalCredentials)) + } + var credentials [32]byte + copy(credentials[:], deposit.WithdrawalCredentials) + proofs[i] = megapool.PendingDepositProof{ + StateSlot: slot, + DepositIndex: index, + Deposit: megapool.ProvedPendingDeposit{ + Pubkey: deposit.Pubkey, + WithdrawalCredentials: credentials, + AmountInGwei: deposit.Amount, + Signature: deposit.Signature, + Slot: deposit.Slot, + }, + Witnesses: ConvertToFixedSize(proofBytes[i]), + } + } + return proofs, megapool.SlotProof{ + Slot: slot, + Witnesses: ConvertToFixedSize(slotProofBytes), + }, nil +} + // PerformanceDefenseProofs bundles everything the RespondWithParticipation // call of a megapool performance challenge needs. type PerformanceDefenseProofs struct { diff --git a/shared/types/api/pdao.go b/shared/types/api/pdao.go index 9d41bfc11..ef0b894d5 100644 --- a/shared/types/api/pdao.go +++ b/shared/types/api/pdao.go @@ -180,6 +180,8 @@ type GetPDAOSettingsResponse struct { UserDistributeDelayWithShortfall uint64 `json:"userDistributeDelayWithShortfall"` PenaltyThreshold *big.Int `json:"penaltyThreshold"` ExitDeficit *big.Int `json:"exitDeficit"` + PrestakeChallengePeriod time.Duration `json:"prestakeChallengePeriod"` + StakeWithoutProofEnabled bool `json:"stakeWithoutProofEnabled"` } `json:"megapool"` Performance struct { diff --git a/shared/types/eth2/fork/electra/pending_deposit_proof_test.go b/shared/types/eth2/fork/electra/pending_deposit_proof_test.go new file mode 100644 index 000000000..ff1159477 --- /dev/null +++ b/shared/types/eth2/fork/electra/pending_deposit_proof_test.go @@ -0,0 +1,15 @@ +package electra + +import ( + "errors" + "testing" + + "github.com/rocket-pool/smartnode/shared/types/eth2/generic" +) + +func TestPendingDepositProofsUnsupported(t *testing.T) { + _, _, err := (&BeaconState{}).PendingDepositProofs([]uint64{0}) + if !errors.Is(err, generic.ErrPendingDepositProofUnsupported) { + t.Fatalf("expected unsupported proof error, got %v", err) + } +} diff --git a/shared/types/eth2/fork/electra/state_electra.go b/shared/types/eth2/fork/electra/state_electra.go index 08ad0c458..54720647b 100644 --- a/shared/types/eth2/fork/electra/state_electra.go +++ b/shared/types/eth2/fork/electra/state_electra.go @@ -275,6 +275,15 @@ func (state *BeaconState) GetValidators() []*generic.Validator { return state.Validators } +func (state *BeaconState) GetPendingDeposits() []*generic.PendingDeposit { + return state.PendingDeposits +} + +// Pending deposit proofs are generated from Gloas progressive lists only. +func (state *BeaconState) PendingDepositProofs([]uint64) ([][][]byte, [][]byte, error) { + return nil, nil, generic.ErrPendingDepositProofUnsupported +} + func (state *BeaconState) GetSlot() uint64 { return state.Slot } diff --git a/shared/types/eth2/fork/fulu/pending_deposit_proof_test.go b/shared/types/eth2/fork/fulu/pending_deposit_proof_test.go new file mode 100644 index 000000000..a76be0f94 --- /dev/null +++ b/shared/types/eth2/fork/fulu/pending_deposit_proof_test.go @@ -0,0 +1,15 @@ +package fulu + +import ( + "errors" + "testing" + + "github.com/rocket-pool/smartnode/shared/types/eth2/generic" +) + +func TestPendingDepositProofsUnsupported(t *testing.T) { + _, _, err := (&BeaconState{}).PendingDepositProofs([]uint64{0}) + if !errors.Is(err, generic.ErrPendingDepositProofUnsupported) { + t.Fatalf("expected unsupported proof error, got %v", err) + } +} diff --git a/shared/types/eth2/fork/fulu/state_fulu.go b/shared/types/eth2/fork/fulu/state_fulu.go index e8b0a70e0..f86c94e85 100644 --- a/shared/types/eth2/fork/fulu/state_fulu.go +++ b/shared/types/eth2/fork/fulu/state_fulu.go @@ -403,6 +403,15 @@ func (state *BeaconState) GetValidators() []*generic.Validator { return state.Validators } +func (state *BeaconState) GetPendingDeposits() []*generic.PendingDeposit { + return state.PendingDeposits +} + +// Pending deposit proofs are generated from Gloas progressive lists only. +func (state *BeaconState) PendingDepositProofs([]uint64) ([][][]byte, [][]byte, error) { + return nil, nil, generic.ErrPendingDepositProofUnsupported +} + func (state *BeaconState) GetSlot() uint64 { return state.Slot } diff --git a/shared/types/eth2/fork/gloas/gloas_proofs_test.go b/shared/types/eth2/fork/gloas/gloas_proofs_test.go index a5c07d718..a9c2d2beb 100644 --- a/shared/types/eth2/fork/gloas/gloas_proofs_test.go +++ b/shared/types/eth2/fork/gloas/gloas_proofs_test.go @@ -2,6 +2,7 @@ package gloas import ( "bytes" + "encoding/binary" "testing" "github.com/pk910/dynamic-ssz/treeproof" @@ -35,6 +36,80 @@ func TestGloasFieldGindices(t *testing.T) { } } +func TestPendingDepositGindices(t *testing.T) { + cases := []struct { + name string + got uint64 + want uint64 + }{ + {"pending_deposits", GetGeneralizedIndexForPendingDeposits(), 2957}, + {"pending_deposits[0]", GetGeneralizedIndexForPendingDeposit(0), 11828}, + {"pending_deposits[1]", GetGeneralizedIndexForPendingDeposit(1), 94632}, + } + for _, tc := range cases { + if tc.got != tc.want { + t.Errorf("%s: got %d want %d", tc.name, tc.got, tc.want) + } + } +} + +func TestPendingDepositProof(t *testing.T) { + state := minimalBeaconState() + state.Slot = 100 + state.PendingDeposits = []*generic.PendingDeposit{ + { + Pubkey: bytes.Repeat([]byte{0x11}, 48), + WithdrawalCredentials: bytes.Repeat([]byte{0x22}, 32), + Amount: 1_000_000_000, + Signature: bytes.Repeat([]byte{0x33}, 96), + Slot: 90, + }, + { + Pubkey: bytes.Repeat([]byte{0x44}, 48), + WithdrawalCredentials: bytes.Repeat([]byte{0x55}, 32), + Amount: 32_000_000_000, + Signature: bytes.Repeat([]byte{0x66}, 96), + Slot: 91, + }, + } + + stateTree, err := generic.SSZ.GetTree(state) + if err != nil { + t.Fatalf("GetTree: %v", err) + } + proof, err := stateTree.Prove(int(GetGeneralizedIndexForPendingDeposit(0))) + if err != nil { + t.Fatalf("Prove: %v", err) + } + leaf, err := generic.SSZ.HashTreeRoot(state.PendingDeposits[0]) + if err != nil { + t.Fatalf("deposit HTR: %v", err) + } + if !bytes.Equal(proof.Leaf, leaf[:]) { + t.Fatal("proof leaf does not match the pending deposit") + } + if ok, err := treeproof.VerifyProof(stateTree.Hash(), proof); err != nil || !ok { + t.Fatalf("verify pending deposit proof: ok=%v err=%v", ok, err) + } + // intoProgressive(0) is two steps. The step nearer the list root mixes in the length. + var length [32]byte + binary.LittleEndian.PutUint64(length[:8], uint64(len(state.PendingDeposits))) + if len(proof.Hashes) < 2 || !bytes.Equal(proof.Hashes[1], length[:]) { + t.Fatalf("expected the list length at witness 1, got %x", proof.Hashes) + } + + depositProofs, slotProof, err := state.PendingDepositProofs([]uint64{0, 1}) + if err != nil { + t.Fatalf("PendingDepositProofs: %v", err) + } + if len(depositProofs) != 2 || len(depositProofs[0]) <= len(proof.Hashes) || len(slotProof) == 0 { + t.Fatalf("expected header-capped proofs, deposits=%d slot=%d", len(depositProofs), len(slotProof)) + } + if !bytes.Equal(depositProofs[0][1], length[:]) { + t.Fatalf("header extension moved the length witness: %x", depositProofs[0][1]) + } +} + func TestValidatorAndSlotProofProgressive(t *testing.T) { state := minimalBeaconState() state.Slot = 100 diff --git a/shared/types/eth2/fork/gloas/state_gloas.go b/shared/types/eth2/fork/gloas/state_gloas.go index 8233917a1..034b37122 100644 --- a/shared/types/eth2/fork/gloas/state_gloas.go +++ b/shared/types/eth2/fork/gloas/state_gloas.go @@ -22,6 +22,7 @@ const ( beaconStateHistoricalSummariesFieldIndex = generic.BeaconStateHistoricalSummariesFieldIndex // 27 beaconStatePreviousEpochParticipationFieldIndex = generic.BeaconStatePreviousEpochParticipationFieldIndex // 15 + beaconStatePendingDepositsFieldIndex = generic.BeaconStatePendingDepositsFieldIndex // 34 // New in Gloas (EIP-7732): payload_expected_withdrawals commits to the // withdrawals of the execution payload bid on at this slot. beaconStatePayloadExpectedWithdrawalsFieldIndex = 44 @@ -207,6 +208,22 @@ func GetGeneralizedIndexForParticipationChunk(chunkIndex uint64) uint64 { ) } +// GetGeneralizedIndexForPendingDeposits returns the gindex of the +// pending_deposits field root inside the Gloas ProgressiveContainer. +func GetGeneralizedIndexForPendingDeposits() uint64 { + return generic.ProgressiveContainerFieldGindex(beaconStatePendingDepositsFieldIndex) +} + +// GetGeneralizedIndexForPendingDeposit returns the gindex of +// pending_deposits[index]. PendingDeposit is a composite element, so each +// list entry is one progressive chunk. +func GetGeneralizedIndexForPendingDeposit(index uint64) uint64 { + return generic.GetGeneralizedIndexForProgressiveListElement( + GetGeneralizedIndexForPendingDeposits(), + index, + ) +} + // ValidatorAndSlotProof produces both the validator proof and the slot proof // for the state's current slot, using EIP-7688 progressive g-indices. func (state *BeaconState) ValidatorAndSlotProof(validatorIndex uint64) ([][]byte, [][]byte, error) { @@ -263,6 +280,70 @@ func (state *BeaconState) ValidatorAndSlotProof(validatorIndex uint64) ([][]byte return validatorProof, slotProof, nil } +// PendingDepositProofs proves pending_deposits[index] for each index, plus the +// state slot. +func (state *BeaconState) PendingDepositProofs(indices []uint64) ([][][]byte, [][]byte, error) { + if len(indices) == 0 { + return nil, nil, nil + } + for _, index := range indices { + if index >= uint64(len(state.PendingDeposits)) || state.PendingDeposits[index] == nil { + return nil, nil, fmt.Errorf("pending deposit index %d out of bounds", index) + } + } + + stateTree, err := generic.SSZ.GetTree(state) + if err != nil { + return nil, nil, fmt.Errorf("could not get state tree: %w", err) + } + + leafProofs := make([][][]byte, len(indices)) + for i, index := range indices { + proof, err := stateTree.Prove(int(GetGeneralizedIndexForPendingDeposit(index))) + if err != nil { + return nil, nil, fmt.Errorf("could not get proof for pending deposit %d: %w", index, err) + } + leaf, err := generic.SSZ.HashTreeRoot(state.PendingDeposits[index]) + if err != nil { + return nil, nil, fmt.Errorf("could not get hash tree root for pending deposit %d: %w", index, err) + } + if !bytes.Equal(proof.Leaf, leaf[:]) { + return nil, nil, fmt.Errorf("proof leaf does not match pending deposit %d", index) + } + leafProofs[i] = proof.Hashes + } + + slotStateProof, err := stateTree.Prove(int(GetGeneralizedIndexForSlot())) + if err != nil { + return nil, nil, fmt.Errorf("could not get proof for slot: %w", err) + } + // Drop the state tree before doing more work so the GC can reclaim it. + stateTree = nil + + if state.LatestBlockHeader == nil { + return nil, nil, fmt.Errorf("latest block header is required") + } + bhTree, err := generic.SSZ.GetTree(state.LatestBlockHeader) + if err != nil { + return nil, nil, fmt.Errorf("could not get block header tree: %w", err) + } + blockHeaderProof, err := bhTree.Prove(int(generic.BeaconBlockHeaderStateRootGeneralizedIndex)) + if err != nil { + return nil, nil, fmt.Errorf("could not get proof for block header: %w", err) + } + + for i := range leafProofs { + combined := make([][]byte, 0, len(leafProofs[i])+len(blockHeaderProof.Hashes)) + combined = append(combined, leafProofs[i]...) + combined = append(combined, blockHeaderProof.Hashes...) + leafProofs[i] = combined + } + slotProof := make([][]byte, 0, len(slotStateProof.Hashes)+len(blockHeaderProof.Hashes)) + slotProof = append(slotProof, slotStateProof.Hashes...) + slotProof = append(slotProof, blockHeaderProof.Hashes...) + return leafProofs, slotProof, nil +} + func (state *BeaconState) blockHeaderToStateProof(blockHeader *generic.BeaconBlockHeader) ([][]byte, error) { generalizedIndex := generic.BeaconBlockHeaderStateRootGeneralizedIndex root, err := generic.SSZ.GetTree(blockHeader) @@ -545,6 +626,10 @@ func (state *BeaconState) GetValidators() []*generic.Validator { return state.Validators } +func (state *BeaconState) GetPendingDeposits() []*generic.PendingDeposit { + return state.PendingDeposits +} + func (state *BeaconState) GetSlot() uint64 { return state.Slot } diff --git a/shared/types/eth2/generic/state.go b/shared/types/eth2/generic/state.go index 062989e47..66afc5c14 100644 --- a/shared/types/eth2/generic/state.go +++ b/shared/types/eth2/generic/state.go @@ -1,5 +1,9 @@ package generic +import "errors" + +var ErrPendingDepositProofUnsupported = errors.New("pending deposit proofs are not supported before gloas") + // Shared BeaconState field offsets. These offsets are stable from Capella through // Gloas for the fields Smart Node proves against; only the *merkleization* of the // parent container changes in Gloas @@ -29,6 +33,9 @@ const BeaconStateStateRootsFieldIndex uint64 = 6 // PreviousEpochParticipation field in the BeaconState struct const BeaconStatePreviousEpochParticipationFieldIndex uint64 = 15 +// BeaconStatePendingDepositsFieldIndex is the field offset of pending_deposits. +const BeaconStatePendingDepositsFieldIndex uint64 = 34 + // BeaconStateParticipationMaxChunks is the chunk count of the epoch // participation byte lists: VALIDATOR_REGISTRY_LIMIT (2^40) one-byte flags // packed 32 per chunk. diff --git a/shared/types/eth2/types.go b/shared/types/eth2/types.go index e566e84d5..2685c00fd 100644 --- a/shared/types/eth2/types.go +++ b/shared/types/eth2/types.go @@ -33,6 +33,10 @@ type BeaconState interface { StateRootProof(slot uint64) ([][]byte, error) BlockHeaderProof() ([][]byte, error) GetValidators() []*generic.Validator + GetPendingDeposits() []*generic.PendingDeposit + // PendingDepositProofs proves each pending deposit and the state slot. + // depositProofs[i] corresponds to indices[i]. The slot proof is shared. + PendingDepositProofs(indices []uint64) (depositProofs [][][]byte, slotProof [][]byte, err error) GetPreviousEpochParticipation() []byte // PreviousEpochParticipationChunkProof proves the previous_epoch_participation // chunk containing validatorIndex's flags up to the state root (no