package morph import ( "errors" "fmt" "os" "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config" morphUtil "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/util" morphClient "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client" "github.com/nspcc-dev/neo-go/pkg/core/native/nativenames" "github.com/nspcc-dev/neo-go/pkg/core/state" "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/rpcclient/actor" "github.com/nspcc-dev/neo-go/pkg/rpcclient/management" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/wallet" "github.com/spf13/cobra" "github.com/spf13/viper" ) type Cache struct { NNSCs *state.Contract GroupKey *keys.PublicKey } type InitializeContext struct { morphUtil.ClientContext Cache // CommitteeAcc is used for retrieving the committee address and the verification script. CommitteeAcc *wallet.Account // ConsensusAcc is used for retrieving the committee address and the verification script. ConsensusAcc *wallet.Account Wallets []*wallet.Wallet // ContractWallet is a wallet for providing the contract group signature. ContractWallet *wallet.Wallet // Accounts contains simple signature accounts in the same order as in Wallets. Accounts []*wallet.Account Contracts map[string]*morphUtil.ContractState Command *cobra.Command ContractPath string ContractURL string } func initializeSideChainCmd(cmd *cobra.Command, _ []string) error { initCtx, err := NewInitializeContext(cmd, viper.GetViper()) if err != nil { return fmt.Errorf("initialization error: %w", err) } defer initCtx.Close() // 1. Transfer funds to committee accounts. cmd.Println("Stage 1: transfer GAS to alphabet nodes.") if err := transferFunds(initCtx); err != nil { return err } cmd.Println("Stage 2: set notary and alphabet nodes in designate contract.") if err := setNotaryAndAlphabetNodes(initCtx); err != nil { return err } // 3. Deploy NNS contract. cmd.Println("Stage 3: deploy NNS contract.") if err := deployNNS(initCtx, deployMethodName); err != nil { return err } // 4. Deploy NeoFS contracts. cmd.Println("Stage 4: deploy NeoFS contracts.") if err := deployContracts(initCtx); err != nil { return err } cmd.Println("Stage 4.1: Transfer GAS to proxy contract.") if err := transferGASToProxy(initCtx); err != nil { return err } cmd.Println("Stage 5: register candidates.") if err := registerCandidates(initCtx); err != nil { return err } cmd.Println("Stage 6: transfer NEO to alphabet contracts.") if err := transferNEOToAlphabetContracts(initCtx); err != nil { return err } cmd.Println("Stage 7: set addresses in NNS.") return setNNS(initCtx) } func (c *InitializeContext) Close() { if local, ok := c.Client.(*morphUtil.LocalClient); ok { err := local.Dump() if err != nil { c.Command.PrintErrf("Can't write dump: %v\n", err) os.Exit(1) } } } func NewInitializeContext(cmd *cobra.Command, v *viper.Viper) (*InitializeContext, error) { walletDir := config.ResolveHomePath(viper.GetString(morphUtil.AlphabetWalletsFlag)) wallets, err := morphUtil.GetAlphabetWallets(v, walletDir) if err != nil { return nil, err } needContracts := cmd.Name() == "update-contracts" || cmd.Name() == "init" var w *wallet.Wallet w, err = getWallet(cmd, v, needContracts, walletDir) if err != nil { return nil, err } c, err := createClient(cmd, v, wallets) if err != nil { return nil, err } committeeAcc, err := morphUtil.GetWalletAccount(wallets[0], morphUtil.CommitteeAccountName) if err != nil { return nil, fmt.Errorf("can't find committee account: %w", err) } consensusAcc, err := morphUtil.GetWalletAccount(wallets[0], morphUtil.ConsensusAccountName) if err != nil { return nil, fmt.Errorf("can't find consensus account: %w", err) } if err := validateInit(cmd); err != nil { return nil, err } ctrPath, err := getContractsPath(cmd, needContracts) if err != nil { return nil, err } var ctrURL string if needContracts { ctrURL, _ = cmd.Flags().GetString(contractsURLFlag) } if err := checkNotaryEnabled(c); err != nil { return nil, err } accounts, err := createWalletAccounts(wallets) if err != nil { return nil, err } cliCtx, err := morphUtil.DefaultClientContext(c, committeeAcc) if err != nil { return nil, fmt.Errorf("client context: %w", err) } initCtx := &InitializeContext{ ClientContext: *cliCtx, ConsensusAcc: consensusAcc, CommitteeAcc: committeeAcc, ContractWallet: w, Wallets: wallets, Accounts: accounts, Command: cmd, Contracts: make(map[string]*morphUtil.ContractState), ContractPath: ctrPath, ContractURL: ctrURL, } if needContracts { err := initCtx.readContracts(fullContractList) if err != nil { return nil, err } } return initCtx, nil } func validateInit(cmd *cobra.Command) error { if cmd.Name() != "init" { return nil } if viper.GetInt64(epochDurationInitFlag) <= 0 { return fmt.Errorf("epoch duration must be positive") } if viper.GetInt64(maxObjectSizeInitFlag) <= 0 { return fmt.Errorf("max object size must be positive") } return nil } func createClient(cmd *cobra.Command, v *viper.Viper, wallets []*wallet.Wallet) (morphUtil.Client, error) { var c morphUtil.Client var err error if ldf := cmd.Flags().Lookup(localDumpFlag); ldf != nil && ldf.Changed { if cmd.Flags().Changed(morphUtil.EndpointFlag) { return nil, fmt.Errorf("`%s` and `%s` flags are mutually exclusive", morphUtil.EndpointFlag, localDumpFlag) } c, err = morphUtil.NewLocalClient(cmd, v, wallets, ldf.Value.String()) } else { c, err = morphUtil.GetN3Client(v) } if err != nil { return nil, fmt.Errorf("can't create N3 client: %w", err) } return c, nil } func getWallet(cmd *cobra.Command, v *viper.Viper, needContracts bool, walletDir string) (*wallet.Wallet, error) { if !needContracts { return nil, nil } return openContractWallet(v, cmd, walletDir) } func getContractsPath(cmd *cobra.Command, needContracts bool) (string, error) { if !needContracts { return "", nil } ctrPath, err := cmd.Flags().GetString(contractsInitFlag) if err != nil { return "", fmt.Errorf("invalid contracts path: %w", err) } return ctrPath, nil } func createWalletAccounts(wallets []*wallet.Wallet) ([]*wallet.Account, error) { accounts := make([]*wallet.Account, len(wallets)) for i, w := range wallets { acc, err := morphUtil.GetWalletAccount(w, morphUtil.SingleAccountName) if err != nil { return nil, fmt.Errorf("wallet %s is invalid (no single account): %w", w.Path(), err) } accounts[i] = acc } return accounts, nil } func (c *InitializeContext) AwaitTx() error { return c.ClientContext.AwaitTx(c.Command) } func (c *InitializeContext) NNSContractState() (*state.Contract, error) { if c.NNSCs != nil { return c.NNSCs, nil } r := management.NewReader(c.ReadOnlyInvoker) cs, err := r.GetContractByID(1) if err != nil { return nil, err } c.NNSCs = cs return cs, nil } func (c *InitializeContext) GetSigner(tryGroup bool, acc *wallet.Account) transaction.Signer { if tryGroup && c.GroupKey != nil { return transaction.Signer{ Account: acc.Contract.ScriptHash(), Scopes: transaction.CustomGroups, AllowedGroups: keys.PublicKeys{c.GroupKey}, } } signer := transaction.Signer{ Account: acc.Contract.ScriptHash(), Scopes: transaction.Global, // Scope is important, as we have nested call to container contract. } if !tryGroup { return signer } nnsCs, err := c.NNSContractState() if err != nil { return signer } groupKey, err := morphUtil.NNSResolveKey(c.ReadOnlyInvoker, nnsCs.Hash, morphClient.NNSGroupKeyName) if err == nil { c.GroupKey = groupKey signer.Scopes = transaction.CustomGroups signer.AllowedGroups = keys.PublicKeys{groupKey} } return signer } // SendCommitteeTx creates transaction from script, signs it by committee nodes and sends it to RPC. // If tryGroup is false, global scope is used for the signer (useful when // working with native contracts). func (c *InitializeContext) SendCommitteeTx(script []byte, tryGroup bool) error { return c.sendMultiTx(script, tryGroup, false) } // SendConsensusTx creates transaction from script, signs it by alphabet nodes and sends it to RPC. // Not that because this is used only after the contracts were initialized and deployed, // we always try to have a group scope. func (c *InitializeContext) SendConsensusTx(script []byte) error { return c.sendMultiTx(script, true, true) } func (c *InitializeContext) sendMultiTx(script []byte, tryGroup bool, withConsensus bool) error { var act *actor.Actor var err error withConsensus = withConsensus && !c.ConsensusAcc.Contract.ScriptHash().Equals(c.CommitteeAcc.ScriptHash()) if tryGroup { // Even for consensus signatures we need the committee to pay. signers := make([]actor.SignerAccount, 1, 2) signers[0] = actor.SignerAccount{ Signer: c.GetSigner(tryGroup, c.CommitteeAcc), Account: c.CommitteeAcc, } if withConsensus { signers = append(signers, actor.SignerAccount{ Signer: c.GetSigner(tryGroup, c.ConsensusAcc), Account: c.ConsensusAcc, }) } act, err = actor.New(c.Client, signers) } else { if withConsensus { panic("BUG: should never happen") } act, err = c.CommitteeAct, nil } if err != nil { return fmt.Errorf("could not create actor: %w", err) } tx, err := act.MakeUnsignedRun(script, []transaction.Attribute{{Type: transaction.HighPriority}}) if err != nil { return fmt.Errorf("could not perform test invocation: %w", err) } if err := c.MultiSign(tx, morphUtil.CommitteeAccountName); err != nil { return err } if withConsensus { if err := c.MultiSign(tx, morphUtil.ConsensusAccountName); err != nil { return err } } return c.SendTx(tx, c.Command, false) } func checkNotaryEnabled(c morphUtil.Client) error { ns, err := c.GetNativeContracts() if err != nil { return fmt.Errorf("can't get native contract hashes: %w", err) } notaryEnabled := false nativeHashes := make(map[string]util.Uint160, len(ns)) for i := range ns { if ns[i].Manifest.Name == nativenames.Notary { notaryEnabled = true } nativeHashes[ns[i].Manifest.Name] = ns[i].Hash } if !notaryEnabled { return errors.New("notary contract must be enabled") } return nil }